/**
cid  ： 课程id ，非课程传-1
extid：产品id, 服务商的时候 extId对应的是
extraId ： 限时购id
*/
import IM from '../../utils/im';
import utils from '../../utils/util';
import config from '../../config';
const CHAT_PAGE_SIZE = 30; //聊天列表每次请求的条数
const SHOW_MSG_LIMIT = 50; //列表保留数据
const RECORD_DISTANCE_TIME = 120; //上报间隔时长

const CHAT_LIST_MSG_TYPE = [
  1,
  2,
  3,
  4,
  11,
  13,
  14,
  15,
  16,
  17,
  18,
  19,
  20,
  21,
  22,
  24,
  31,
  32,
  33,
  34,
  35,
  36,
  37,
  64,
  65,
  66,
  68,
  70,
  71,
  73,
  74,
  75,
  76,
  80,
  81,
  82
]; //聊天区显示消息类型
Page({
  /**
   * 页面的初始数据
   */
  data: {
    videoTotalTime: 0,
    videoCurrentTime: 0,
    videoProgressPercent: 0,
    videoSourceList: [{ //线路列表
        title: "线路1",
        url: ""
      },
      {
        title: "线路2",
        url: ""
      }
    ],
    videoSourceIndex: 0, //线路索引
    videoStatus: -1, //当前音频播放状态 0暂停 1播放 2加载 3结束 -1 播放器已初始化完成但是用户还没点击开始
    isShowVideoSourceList: false,
    isVideoFullScreen: false,

    isShowPlayerModeList: false,
    playerModeList: [{ //清晰度列表
        title: "流畅",
        url: ""
      },
      {
        title: "原画",
        url: ""
      }
    ],
    playerModeIndex: 0, //清晰度索引
    playerStatus: -1, //当前音频播放状态 0暂停 1播放  -1 播放器已初始化完成但是用户还没点击开始
    isPlayerFullScreen: false, //live-player是否属于全屏

    liveId: 0, //直播id
    socialRoomId: 0, //社群的id
    userId: "", // 用户id
    moduleType: 1, //1是大班课  2是独立直播间
    detailId: 0, //有detailId 是独立直播间



    isChatListPullDownLoading: false, //讨论区下拉是否属于加载中
    isChatListPullUpLoading: false, //讨论区上拉是否属于加载中


    isTeaChatListPullDownLoading: false,
    isTeaChatListPullUpLoading: false,
    roles: {}, //当前用户角色
    socialInfo: {}, //社群信息
    liveInfo: {}, //直播信息
    otherInfo: {}, //直播其他参数信息
    sensitiveWord: [], //敏感词组
    scrollToChatView: "", //scroll-view 滚动底部 J_scrollToChatView
    teaChatList: [], //授课区列表
    chatList: [], //聊天区列表
    dmScrollTop: 0, //弹幕列表滚动位置
    chatScrollTop: 0, //聊天列表滚动位置
    teaScrollTop: 0, //授课区滚动的位置
    isGroupTaboo: false, //是否群禁言
    isSelfTaboo: false, //是否自己禁言
    chatInputVal: "",
    newMsgStack: [], //新消息
    isShowChatPopup: false, //聊天弹窗是否显示
    chatTabList: [{
      title: "授课区",
      val: 1
    }],
    companyShare: {}, //全局通用变量
    chatTabIndex: 1,
    systemInfo: {}, //系统信息
    isShowMore: false, //是否显示更多
    liveDownCount: null, //直播倒计时
    isSubscribeLive: false, //是否订阅了
    isShowSubscribeQrCode: false, //是否显示二维码弹框
    subscribeQrCodeUrl: "", //订阅二维码的链接
    isShowLiveDesc: false, //是否显示直播间接
    liveDesc: "", //直播简介
    playbackRate: [0.5, 1, 1.25, 1.5, 2],
    playbackRateIndex: 1,
    isShowTalentRank: false, //达人榜是否显示
    isShowTalentRankRoster: false, // 达人榜单
    isShowInvitationCard: false, //是否显示邀请卡
    isAllowPraise: false, //是否允许点赞
    isShowBrushViewCount: false, //是否显示刷人数弹框
    isShowBusinessCard: false, //是否显示名片弹框
    isShowEndLive: false, //是否显示结束直播弹框
    isShowStuCommerceList: false, //是否显示学生带货列表
    isShowTeaCommerceList: false, //是否显示讲师带货列表
    isShowCommerceFloat: false, //是否显示带货浮窗
    isShowCommerceCouponFloat: false, //是否显示优惠券浮窗
    commerceFloatInfo: {}, //带货浮窗
    commerceFloatCouponInfo: {}, //带货浮窗优惠券
    showIntegrate: false, //获取积分提示
    integrateCount: 0, //领取积分
    // isShowLmConfirm:false, //是否显示连麦confirm
    isShowLianMaiQrcodeModal: false,
    isShowLmGraspModal: false, //是否显示抢麦的效果
    graspMicSetTime: 0, //抢麦设置倒计时
    graspMicTimeCount: 0, //抢麦计时数
    isGraspMicEntryShow: false, //抢麦入口是否显示
    isShowToolBar: false, // 播放器进度条
    isClearScreenOther: false, //其他的清屏
    praiseNUm: 0, //点赞次数
    praiseTime: 0, //点赞计算时间
    likeNum: 0,
    praiseFlag: true, //点赞
    lmPathQuety: "",
    overTenThousand: 0, //点赞数转换
    praiseTimer: null, //点赞时间累积
    isPraiseAniming: false, //点赞是否正在点击
    liveReviewCover: {},
    isShowAddressList: false, //是否显示收货地址
    isShowMallSpecs: false, //是否显示商城规格
    isShowOtherPlaceOrder: false, //是否显示其他下单页面
    otherPlaceOrderParams: {}, //虚拟商品下单组件参数
    mallSpecsParams: {}, //商城规格组件参数
    isShowMallPlaceOrder: false, //是否显示商城下单组件
    mallPlaceOrderParams: {}, //商城下单参数
    addressInfo: "", //收货地址信息
    inputObj: { //input 输入框动态属性
      placeHolder: "说点什么...",
      disabled: false,
    },
    currLuckyDraw: {}, //当前抽奖信息
    rewardRoles: [], //打赏的角色 讲师+嘉宾
    rewardAnimMsg: null, //打赏消息
    welfareNum: 0, // 剩余可领取的福利
    isShowFormCom: false, //是否显示表单弹框
    formComParams: {}, //关联表单参数对象
    isShowGuideDataQrcode: false, // 是否显示讲师弹框二维码
  },



  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    if (!options.liveId || options.liveId == 'undefined') {
      options.liveId = 667930;
      options.socialRoomId = 812863;
      utils.setEnvConfig(3);
      utils.setStorage("roomToken", 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vZm9ybWFsYXBpLmNranIwMDEuY29tL2FwaS9wYy9sb2dpbi9oYXNRcmNvZGVMb2dpbmVkIiwiaWF0IjoxNjg2ODE0OTYzLCJleHAiOjE2ODk0MDY5NjMsIm5iZiI6MTY4NjgxNDk2MywianRpIjoiRDNQUW5UQ3F1ZnlBTXVvYyIsInN1YiI6bnVsbCwiYyI6Im5rcWUiLCJ1IjoibXY2OGU4NSIsImEiOjEsInAiOm51bGwsInJmdCI6MTY4NjYxODc3NiwidWlkIjoiMTQ0MjI2MDg1MjE1NzI2Nzk3MCIsImN2IjoxMDAsInV0eSI6MiwiYWlkIjoiMTQ0MjI2MDg1MjE1NzI2Nzk3MCIsImNpZCI6IjE0MjA2MjcxNTU1NjU0NTMzMTMiLCJsaXZlQXV0aElkIjowLCJpc21iIjowLCJwcnYiOiI4N2UwYWYxZWY5ZmQxNTgxMmZkZWM5NzE1M2ExNGUwYjA0NzU0NmFhIiwic3lzIjoibWljcm8iLCJhdWkiOjEwMDI1LCJhcHBJZCI6IjE0NDIyOTkyNDMyODY4OTI1NDUiLCJsb2dpblVzZXJUeXBlIjoyLCJhZyI6OTMyNzA4fQ.C9HR7NoNu-khcjCdJorC3DMoFgQ-aXQwIcML8YWuCzU');
    }
    this._opts = options;
    this._initPrivateData();
    let systemInfo = utils.getStorage("systemInfo");

    this.setData({
      systemInfo: systemInfo
    });
    utils.get('company/share').then(res => {
      this.setData({
        companyShare: res
      })
      utils.setStorage('companyShare', res);
    });
    this._bindPhoneSetting = {};
    this._bindPhoneComponent = this.selectComponent("#bindPhone");
    this._bindPhoneSetting = await utils.getBindPhoneSetting(options.detailId ? config.ckFrom.personalLive : config.ckFrom.live);
    if (this._bindPhoneSetting.getBind) {
      this._bindPhoneComponent.showForm({
        type: 3
      });
    } else {
      Promise.all([this._getSocialInfo(), this._getHLS()]).then(values => {
        this._initOtherData(values).then(() => {
          this._render();
        });
      });
    }
    setTimeout(() => {
      // this.selectComponent("#attendPrizeList").show({type:64});
      // this.selectComponent("#attendResult").show({activityType:64,id:2248});
      // this.selectComponent("#attendGuide").show();
      // this.selectComponent("#reward").show();
      // this.openReward();
      // this.selectComponent("#attendPrizeList").show({
      //   type: 128
      // });
      // this.selectComponent("#attendResult").show({
      //   id: 2197,
      //   activityType: 64
      // });
      // this.setData({
      //   isShowFormCom: true
      // })
    }, 3000)
  },
  //其他的数据
  _initOtherData(values) {
    return new Promise((resolve) => {
      let socialInfo = values[0];
      let liveInfo = values[1];
      let options = this._opts;
      let liveReviewCover = {};
      console.log("Promise.all", socialInfo, liveInfo)
      let roles = utils.getRoles(socialInfo.role, socialInfo.subRole);
      let rewardRoles = this.getRewardRoles(socialInfo.lectures, socialInfo.admin);
      liveInfo.playURL = liveInfo.playURL ? utils.decrypt(liveInfo.playURL) : '';
      liveInfo.playURL480p = liveInfo.playURL480p ? utils.decrypt(liveInfo.playURL480p) : '';
      liveInfo.reviewURL = liveInfo.reviewURL ? utils.decrypt(liveInfo.reviewURL) : '';
      liveInfo.reviewURLMp4 = liveInfo.reviewURLMp4 ? utils.decrypt(liveInfo.reviewURLMp4) : '';
      liveInfo.liveMp4 = liveInfo.liveMp4 ? utils.decrypt(liveInfo.liveMp4) : ''; //录播地址
      liveInfo.liveM3u8 = liveInfo.liveM3u8 ? utils.decrypt(liveInfo.liveM3u8) : ''; //录播地址
      //录播的时候  转化 reviewURL
      if (liveInfo.liveType == 0) {
        liveInfo.reviewURL = liveInfo.liveM3u8 || liveInfo.liveMp4;
        liveInfo.reviewURLMp4 = liveInfo.liveMp4 || liveInfo.liveM3u8;
      }
      //直播的时候转化格式
      if (liveInfo.status == 1) {
        if (liveInfo.liveSubType == 2) {
          //快直播转化flv格式
          liveInfo.playURL = 'https://' + liveInfo.playURL.replace(/^(webrtc:\/\/)|(\?[^]*)$/g, '') + '.flv';
          liveInfo.playURL480p = 'https://' + liveInfo.playURL480p.replace(/^(webrtc:\/\/)|(\?[^]*)$/g, '') + '.flv';
        } else if (liveInfo.liveType != 0) {
          //录播不转
          liveInfo.playURL = liveInfo.playURL.replace(/(.m3u8)$/g, '.flv');
          liveInfo.playURL480p = liveInfo.playURL480p.replace(/(.m3u8)$/g, '.flv');
        }
      }
      if (liveInfo.status >= 2) {
        liveReviewCover = this._getLiveReviewCover(liveInfo)
      }
      console.log("liveInfo", liveInfo)

      liveInfo.isDataReady = true;

      this.data.playerModeList[0].url = liveInfo.playURL480p; //直播中标清
      this.data.playerModeList[1].url = liveInfo.playURL; //直播中原画

      this.data.videoSourceList[0].url = liveInfo.reviewURL; //m3u8
      this.data.videoSourceList[1].url = liveInfo.reviewURLMp4; // mp4

      liveInfo.welcomeMessage = liveInfo.welcomeMessage && liveInfo.welcomeMessage.split('\n'); //欢迎语


      this._tags = this._getTags(socialInfo.role, socialInfo.subRole, socialInfo.tag);
      //IM默认发送的数据
      this._imSendDefaultData = {
        talkType: (roles.isTeacher || roles.isAdmin) ? 1 : -1,
        roomId: options.socialRoomId, //社群ID
        jimRoomId: socialInfo.jgChatRoomId, //极光房间号
        jiguangUserName: socialInfo.jiguangUserName, //消息发送者userID
        userRole: socialInfo.role,
        subRole: socialInfo.subRole,
        tag: this._tags.tag,
        avatar: socialInfo.avatar,
        nickname: socialInfo.nickname,
        realName: socialInfo.realName,
        userName: socialInfo.userName,
        userRealName: socialInfo.userRealName,
        isOwnApplet: 1,
      }
      if (this._opts.detailId) {
        this._imSendDefaultData.detailId = this._opts.detailId;
      }
      if (liveInfo.isHideTalk != 1 || roles.isTeacher || roles.isAdmin) {
        this.data.chatTabList.push({
          title: "讨论区",
          val: 2
        })
      }

      this.setData({
        liveId: options.liveId,
        socialRoomId: options.socialRoomId,
        detailId: options.detailId || 0,
        moduleType: options.detailId ? 2 : 1,
        socialInfo: socialInfo,
        liveInfo: liveInfo,
        roles: roles,
        userId: this.data.companyShare.userId,
        playerModeList: this.data.playerModeList,
        playerModeIndex: liveInfo.definitionType == 2 ? 1 : 0,
        videoSourceList: this.data.videoSourceList,
        isShowToolBar: liveInfo.playType == 1 ? true : false,
        likeNum: liveInfo.likeNum,
        liveReviewCover: liveReviewCover,
        chatTabList: this.data.chatTabList,
        rewardRoles: rewardRoles
      }, () => {
        resolve();
      });
    })
  },
  rewardAnim() {
    if (this._isRewardAniming || !this._rewardAnimMsgStock.length) return;
    this._isRewardAniming = true;
    this.setData({
      rewardAnimMsg: this._rewardAnimMsgStock.shift()
    }, () => {
      this.animate('#J_reward-anim-box', [{
          opacity: 0.0,
          translateX: -1000,
          ease: 'ease-out'
        },
        {
          opacity: 1,
          translateX: 0,
          ease: 'ease-out'
        },
      ], 750, function () {
        this.animate('#J_reward-num', [{
            scale: [1, 1]
          },
          {
            scale: [1.5, 1.5],
          },
          {
            scale: [1, 1]
          },
        ], 500, function () {
          this.clearAnimation('#J_reward-num', {
            scale: true
          });
          setTimeout(() => {
            this.clearAnimation('#J_reward-anim-box', {
              opacity: true,
              rotate: true,
              translateX: true
            }, () => {
              this._isRewardAniming = false;
              if (!this._rewardAnimMsgStock.length) {
                this.setData({
                  rewardAnimMsg: null
                })
              } else {
                this.rewardAnim();
              }
            });
          }, 500)
        }.bind(this))
      }.bind(this))
    })
  },
  async _render() {
    let socialInfo = this.data.socialInfo;
    let liveInfo = this.data.liveInfo;
    let liveId = this.data.liveId;
    let moduleType = this.data.moduleType;


    if (liveInfo.status >= 1) {
      this._videoCtx = wx.createVideoContext("J_live-video")
      this._playerCtx = wx.createLivePlayerContext("J_live-player");
    }
    //登录IM
    IM.login({
      userID: socialInfo.jgInit.userId,
      userSig: socialInfo.jgInit.signature,
      groupID: socialInfo.jgChatRoomId,
      receivedMsgCB: this._handlerIMMessage,
      ctx: this,
      errors: {
        liveId: liveId
      }
    });
    //大班课才有倒计时
    if (moduleType == 1) {
      this.liveTimeDownCount();
    }
    await this._getMsgFilterList();
    if (!liveInfo.isHideHistoryMsg || this.data.roles.isTeacher || this.data.roles.isAdmin) {
      this.getChatHistoryList().then(() => {
        this.dmScrollToBottom();
      });
    }
    this.showOverTenThousand()
    this.getTeaChatHistoryList();
    this.setIsAllowDragProgressBar();
    //是否群禁言
    this._setGroupTaboo(socialInfo.memberPrivileges);
    //获取签名
    utils.get('imageSign').then(res => {
      this._aLiYunISP = res;
    });
    //获取到货浮窗
    this._getLiveBringGoods();

    //连麦
    let lmPathQuety = this.getLianMianXcxQuery();
    this.setData({
      lmPathQuety: lmPathQuety
    });
    //课件图
    if (liveInfo.isShowWareImg == 1 && liveInfo.material) {
      let material = JSON.parse(liveInfo.material);
      this.data.chatTabList.push({
        title: "课件图",
        val: 3
      });
      this.setData({
        chatTabList: this.data.chatTabList,
        'liveInfo.material': material
      })
    }
    //获取直播其他信息
    this._getLiveRoomOther();
    //抽奖信息
    if (liveInfo.lotteryId) {
      this.setData({
        currLuckyDraw: {
          lotteryId: liveInfo.lotteryId, //当前正在抽奖的id
          lotteryDrawAt: liveInfo.lotteryDrawAt,
          lotteryDownCount: utils.dtFormat(liveInfo.lotteryDrawAt * 1000, 'mm:ss'),
          lotteryJoin: liveInfo.lotteryJoin
        }
      })
      if (!this._ldcTimer) {
        this._luckyDrawDownCount();
      }
    }
    setTimeout(() => {
      if (liveInfo.status >= 2) {
        this._getElemClientRect("#J_progress-holder").then(res => {
          this._progressHolderRect = res;
        });
      }
      //弹幕滚动元素信息
      this._getElemClientRect("#J_dm-scroll").then(res => {
        this._dmScrollViewRect = res;
      });
    }, 2000)
    //直播间加入场次
    if (this.data.moduleType == 2 && liveInfo.isInDetailMember != 1) {
      utils.post(`live/livePersonal/addDetailMember/${this.data.liveId}`, {
        detailId: this.data.detailId
      }, false)
    }
    // 直播中开始统计时长
    if (liveInfo.status > 0) {
      this._startLiveTimeCount();
    }
  },
  //私有变量
  _initPrivateData() {
    this._videoCtx = null; //video上下文
    this._playerCtx = null; //live-player上下文
    this._progressHolderRect = {} //进度条hodler的elem信息
    this._videoDuration = 0; //video视频总时长
    this._videoSeekTime = 0; //当前视频播放的拖动改的节点
    this._videoCurrentTime = 0; //当前播放器的播放节点
    this._historySort = "desc"; //聊天区分页排序
    this._teaHistorySort = "desc"; //授课区分页排序
    this._chatScrollMessageId = 0; //聊天从哪条信息开始取
    this._teaChatScrollMessageId = 0; //授课区从哪条信息开始取
    this._sensitiveWord = []; //敏感词组
    this._imSendDefaultData = {}; //发送默认的数据
    this._tags = {}; //标签
    this._isChatListPullDownHasMore = false; //讨论区下拉加载是否还有多数据
    this._isChatListPullDownRequesting = false; //讨论区下拉是否再请求中
    this._isChatListPullUpHasMore = false; //讨论区上拉是否还有更多
    this._isChatListPullUpRequesting = false; //讨论区上拉是否再请求中
    this._isTeaChatListPullDownHasMore = false; //授课区是下拉是否还有更多数据
    this._isTeaChatListPullDownRequesting = false; //授课区下拉是否再请求中
    this._isTeaChatListPullUpHasMore = false; //授课区是下拉是否还有更多数据
    this._isTeaChatListPullUpRequesting = false; //授课区上拉是否再请求中
    this._isDmScrollAtBottom = false; //弹幕是否滚动到底部
    this._isChatScrollAtBottom = false; //聊天区是否滚动底部
    this._dmChatListRect = {}; //弹幕列表元素信息
    this._chatListRect = {}; //讨论区列表元素信息
    this._teaListRect = {}; //授课区列表元素信息
    this._dmScrollViewRect = {};
    this._userSecret = wx.getStorageSync('userSecret');
    this._liveWatchTimeCount = 0; //观看时长统计
    this._liveGetPointTimeCount = 0; //获取积分时长统计
    this._liveWatchTimeCountTimer = null; //观看时长计时器, //观看多久
    this._isIos = utils.isIos(); //
    this._isAllowDragProgressBar = true; //是否允许拖动进度条  isAllowProgressBar, // 录播的时候（直播进行中）是否允许拖动进度条 isPlayBackAllowBar, //回放是否允许拖动进度条
    this._rewardAnimMsgStock = []; //打赏消息
  },
  //发送讲师二维码
  sendWxQrcode() {
    IM.sendCustomMessage({
      socialRoomMessageId: new Date().getTime(),
      ...this._imSendDefaultData,
      msgType: 94,
      content: 1
    }).then(() => {
      this.setData({
        isShowMore: false
      })
      wx.showToast({
        title: '发送成功',
      })
    })
  },
  //获取打赏的角色
  getRewardRoles(lecture, admin) {
    let res = [...lecture]
    if (admin) {
      let role = utils.getRoles(admin.userRole, admin.subRole);
      if (role.isGuest) res.push(admin);
    }
    res.forEach(item => {
      item = this.getDynamicName(item)
    })
    return res;
  },
  //设置是否允许拖动进度
  setIsAllowDragProgressBar() {
    //录播直播中设置允许拖动进度，回放一直可以拖动进度(isPlayBackAllowBar=1)   正常直播只对回放进行设置
    let flag = true;
    let liveInfo = this.data.liveInfo;
    if (liveInfo.status == 2 && !liveInfo.isPlayBackAllowBar && !liveInfo.playHistoryIsFinish) {
      //回放的时候 禁止拖动()
      flag = false;
    } else if (liveInfo.liveType == 0) {
      //录播比较特殊，字段不一致
      if (liveInfo.status == 1 && !liveInfo.isAllowProgressBar) {
        //直播中
        flag = false;
      }
    }
    this._isAllowDragProgressBar = flag;
    console.log("this._isAllowDragProgressBar", this._isAllowDragProgressBar)
  },
  //设置input的信息
  _setInputObj() {
    let isGroupTaboo = this.data.isGroupTaboo,
      isSelfTaboo = this.data.isSelfTaboo,
      inputObj = this.data.inputObj,
      roles = this.data.roles;
    if (!roles.isTeacher && !roles.isAdmin) {
      if (isGroupTaboo) {
        inputObj.placeHolder = "群禁言中";
        inputObj.disabled = true;
      } else if (isSelfTaboo) {
        inputObj.placeHolder = "你已被禁言";
        inputObj.disabled = true;
      } else {
        inputObj.placeHolder = "说点什么...";
        inputObj.disabled = false;
      }
    }
    // if (this.data.moduleType == 2 && this.data.liveInfo.status >= 2) {
    //   inputObj.placeHolder = "回放不支持评论";
    //   inputObj.disabled = true;
    // }
    this.setData({
      inputObj: this.data.inputObj
    })
  },
  //打开商城规格
  openMallSpecs(data) {
    console.log("openMallSpecs", data);
    this.exitFullScreen();
    this.setData({
      isShowMallSpecs: true,
      mallSpecsParams: data
    })
  },
  mallPaceOrderSuccess() {
    console.log("mallPaceOrderSuccess");
    this.setData({
      isShowMallSpecs: false
    });

    let prizeListComponent = this.selectComponent("#attendPrizeList");
    console.log("prizeListComponent", prizeListComponent, prizeListComponent.data)
    if (prizeListComponent && prizeListComponent.data.isShow) {
      prizeListComponent.refresh();
    }
    let attendResultComponent = this.selectComponent("#attendResult");
    if (prizeListComponent) {
      attendResultComponent.hideAll();
    }
  },
  //商城规格确认
  specsConfirm(e) {
    let data = e.detail;
    this.setData({
      mallPlaceOrderParams: data
    }, () => {
      this.setData({
        isShowMallPlaceOrder: true
      })
    })
  },
  getActivityPrize(e) {
    console.log(e);
    let data = e.detail;
    this.setData({
      mallPlaceOrderParams: data,
      isShowMallPlaceOrder: true
    })
  },
  //手机号绑定成功
  bindPhoneSuccess(e) {
    let data = e.detail;
    if (data.type == 3) {
      this.onLoad(this._opts)
    }
  },
  //关联表单提交成功回调
  formComSubmitSuccess(e) {
    console.log("formComSubmitSuccess", e, this._payShowInfo);
    this.setData({
      isShowFormCom: false
    })
    let data = e.detail;
    if (data.ckFrom != 12 && data.ckFrom != 13 && data.ckFrom != 76) {
      //虚拟商品
      this.openOtherPlaceOrder(this._payShowInfo);
    } else {
      wx.showToast({
        title: '提交成功',
        icon: "none"
      })
    }
  },
  //打开二维码
  openGuidanceQrCode(){
    this.selectComponent("#guidanceGroupQrcode").open();
  },
  openBindPhone(){
    this._bindPhoneComponent.showForm();
  },
  /*
   *  ┌─────────────────────────────────────────────────────────────┐
   *  @@ 带货跳转相关 start
   *  └─────────────────────────────────────────────────────────────┘
   *  商城商品0元直接支付成功
   */
  //带货跳转|| 者去购买|| 者是否需要提前填写表单  || 绑定手机号码
  async switchBuyGuide(e) {
    console.log("switchBuyGuide", {
      ...e.detail
    });
    let data = e.detail;
    let otherInfo = this.data.otherInfo;
    data.payType = data.payType || payType.voiceDuration; //历史聊天列表的时候用payType，发送消息的时候可能是voiceDuration
    data.prodType = data.prodType || data.subProdType;
    data.id = data.subMsgId || data.id; //发送的时候没有id  聊天列表没有又subMsgId
    data.presale = data.presale || data.amount
    data.courseType = data.courseType ? (data.courseType + '').toString() : (data.voiceStatus + '').toString() || '';
    data.socialRoomId = this.data.socialRoomId;
    this._switchBuyGuideData = data;
    if (this.data.moduleType == 1 || (this.data.moduleType == 2 && this.data.liveInfo.status < 2)) {
      this._sendCommerceImMsg(data.content || data.name);
    }
    //没有开启二级商务直接跳转出去
    if (otherInfo.isEnableAppletSubMch * 1 == 0) {
      this.openContactGuide(data);
      return;
    }
    //实体商品
    if (data.prodType == 12 || data.prodType == 13) {
      //商城商品
      if (data.payType == 1 || data.presale) {
        //1: 免费:2: 收费:3: 密码支付  4小班课的审核加入
        this.openContactGuide(data);
        return;
      }
      let sendData = {
        isLive: 1,
        mgId: data.id,
        socialRoomId: this.data.socialRoomId,
      }
      if (this.data.detailId) {
        sendData.detailId = this.data.detailId;
      }
      let bindPhoneSetting = await utils.getBindPhoneSetting(config.ckFrom.shopping);
      if (bindPhoneSetting.buyBind || bindPhoneSetting.collectBind) {
        this._bindPhoneComponent.showForm();
        return;
      }
      utils.get(`goods/goodsDetail`, sendData).then(res => {
        if (res.status == 'error') {
          wx.showToast({
            title: res.msg,
          });
          return;
        }
        //商城商品
        let companyShare = this.data.companyShare;
        let isInCollage = this.checkIsInCollage(res.collage, companyShare),
          isFlashSales = this.checkIsFlashSales(res.flashSales, companyShare),
          isBargain = res.bargain;
        if (isInCollage || isFlashSales || isBargain || res.isRelForm) {
          //拼团，限时购、砍价、绑定手机号、关联表单
          this.openContactGuide(data);
        } else {
          this.openMallSpecs(res);
        }
      })
    } else {
      //虚拟商品
      let args = this._getVirtualRequestArgs(data);
      let ckFrom = args.ckFrom;
      let aaId = ''; //申请服务商后端返回的参数
      //vip和svip都是ckFrom=1,如果是限时购vip和svip则ckFrom=68
      if (ckFrom == config.ckFrom.svip || ckFrom == config.ckFrom.vip) {
        ckFrom = 1;
      }
      if (!this._isCanBuyInLive(data.payType, data.prodType, data.relationType)) {
        console.log("不能再直播间购买")
        this.openContactGuide(data);
        return;
      }
      let bindPhoneSetting = await utils.getBindPhoneSetting(ckFrom);
      if (bindPhoneSetting.buyBind) {
        this._bindPhoneComponent.showForm();
        return;
      }
      //购买服务商类型
      if (Object.values(config.ckFrom.agentApplys).includes(ckFrom)) {
        //服务商,判断是升级服务商还是降级
        if (args.extId > this.data.companyShare.userVipType) {
          //升级购买
          let applyInfo = await utils.post("members/applySave", {
            applyType: args.extId, //申请的服务商身份
            name: this.data.socialInfo.userName, //用户昵称
            realName: this.data.socialInfo.realName, //用户真名
            mobile: this.data.companyShare.userMobile, //用户手机号
            applyStatus: 2, //线上付费升级
            from: 3 //3：直播，1：申请入口申请
          })
          console.log("applyInfo", applyInfo);
          aaId = applyInfo.aaId;
        } else {
          //不能购买降级
          let titlTxt = args.extId == this.data.companyShare.userVipType ? '您已是服务商身份，无需重复购买' : '服务商身份不支持降级购买';
          wx.showToast({
            title: titlTxt,
            icon: "none",
            duration: 2000
          });
          return false;
        }
      }
      //关联表单
      if (args.ckFrom == 76) {
        //关联表单不用请求payShow
        this.setData({
          formComParams: {
            relId: data.id,
            type: 2,
            relType: 2, // 1报名保单 2调研表单  3其他商品类型的表单（ckFrom去map配置config的formRelateType）
            otherParams: {
              ckFrom: ckFrom
            }
          }
        }, () => {
          console.log("this.data.formComParams", this.data.formComParams);
          this.setData({
            isShowFormCom: true
          });
        })
        return;
      }
      utils.get("common/payShow", {
        ...args,
        ckFrom: ckFrom
      }).then(res => {
        if (res.status == 2) {
          wx.showToast({
            title: res.msg,
            icon: "none"
          });
          return;
        };
        this._payShowInfo = res;
        this._payShowInfo.otherParams = {
          courseType: data.courseType,
          prodType: args.ckFrom,
          extId: args.extId,
          cId: args.cId,
          relationType: data.relationType,
          extraId: args.extraId
        }
        if (aaId) {
          res.otherParams.aaId = aaId;
        }
        if (this._isCanBuyInLive(data.payType, data.prodType, data.relationType)) {
          if (this._isIos) {
            this.openContactGuide(data);
          } else if (this._payShowInfo.goods[0].isFreeGood == 1) {
            this.openContactGuide(data);
          } else {
            //hasFormLog 是否填写过表单  collectPage:1购买前 2购买后 3 非强制  enableEdit:1不支持修改 2 支持修改
            let isRelateForm = this._payShowInfo.basic && this._payShowInfo.basic.liveRelateForm == 3 && this._payShowInfo.basic.liveRelateCollect == 1; //是否关联表单
            if (isRelateForm) {
              //关联表单填写
              let prodType = data.prodType;
              if (prodType == 5) {
                //课程类的
                prodType = `5-${data.courseType}`
              }
              console.log("prodType", prodType, config.formRelateType[prodType])
              this.setData({
                formComParams: {
                  relId: data.id,
                  type: 1,
                  relType: config.formRelateType[prodType], // 1报名保单 2调研表单  3其他商品类型的表单（ckFrom去map配置config的formRelateType）
                  otherParams: {
                    ckFrom: ckFrom
                  }
                }
              }, () => {
                console.log("this.data.formComParams", this.data.forswitchBuyGuidemComParams);
                this.setData({
                  isShowFormCom: true
                });
              })
            } else {
              this.openOtherPlaceOrder(this._payShowInfo);
            }
          }
        } else {
          this.openContactGuide(data);
        }
      }).catch(() => {
        // this.openContactGuide(data);
      })
    }
  },
  otherPlaceOrderPaySuccess() {
    this.setData({
      isShowOtherPlaceOrder: false,
      isShowStuCommerceList: false
    });
    this.selectComponent("#reward").hide();
  },
  //发送带货信息
  _sendCommerceImMsg(name) {
    IM.sendCustomMessage({
      socialRoomMessageId: new Date().getTime(),
      ...this._imSendDefaultData,
      msgType: 75,
      content: name
    })
  },
  //检查是否开启限时购
  checkIsFlashSales(data, companyShare) {
    if (!data || companyShare.companyAuth.enableFlashSalesModule != 1) {
      return false;
    }
    if (!data.sales) {
      return false;
    }
    let nt = new Date().getTime();
    let st = utils.getTimeByDate(data.sales.startTime);
    let et = utils.getTimeByDate(data.sales.endTime);
    if (nt >= st && nt < et && data.sales.status > -1) {
      return true;
    }
    return false;
  },

  //检查是否正在拼团中
  checkIsInCollage(data, companyShare) {
    if (!data || companyShare.companyAuth.enableCollage != 1) {
      return false;
    }
    let nt = new Date().getTime();
    let st = utils.getTimeByDate(data.startTime);
    let et = utils.getTimeByDate(data.endTime);
    //当前时间在开始时间和结束时间之间并且拼团状态>-1
    if (nt >= st && nt < et && data.status > -1) {
      return true;
    }
    if (nt < st && data.status == 1) {
      return true;
    }
    return false;
  },
  //获取虚拟请求的函数参数
  _getVirtualRequestArgs(data) {
    console.log("_getVirtualRequestArgs", data);
    let mapData = {
      isLive: 1,
      cId: -1,
      ckFrom: data.prodType,
      extId: data.id,
      relationType: data.relationType,
      relationId: data.relationId,
      extraId: data.pId || '',
      socialRoomId: this.data.socialRoomId
    };
    if (data.prodType == config.ckFrom.course) {
      mapData.cId = data.id;
      mapData.extId = -1
    } else if (Object.values(config.ckFrom.agentApplys).includes(data.prodType)) {
      //服务商
      mapData.extId = data.vipType || data.subName
      mapData.courseType = data.courseType || data.voiceStatus;
    } else if (data.prodType == config.ckFrom.form) {
      mapData.cId = data.id;
    }
    if (data.relationType == config.relationTypeMap.flashSales) {
      mapData.mtkType = 1;
    }
    if (this.data.detailId) {
      mapData.detailId = this.data.detailId;
    }
    console.log("_getVirtualRequestArgs", data, mapData);
    return mapData;
  },
  //客服引导下单页面
  openContactGuide(data) {
    console.log("openContactGuide", data);
    let socialRoomId = this.data.socialRoomId;
    let argsData = {};
    if (data.prodId || data.id) {
      argsData = {
        socialRoomId: socialRoomId,
        prodId: data.prodId || data.id,
        prodType: data.prodType,
        subProdId: data.subProdId,
        subProdType: data.subProdType,
        relationId: data.relationId,
        relationType: data.relationType
      }
    } else {
      argsData = {
        socialRoomId: socialRoomId,
        prodType: data.prodType
      }
    }

    if (data.voiceStatus !== '') {
      argsData.courseType = data.voiceStatus
    }
    if (this.data.detailId) {
      argsData.detailId = this.data.detailId;
    }
    this.exitFullScreen();
    utils.navigateToGuide(argsData);
  },
  //是否能再直播间内购买
  /**
    拼团、限时购、活动、表单、预约、面授课、小班课（审核加入）=》不能直接购买部
    绑定手机号码的商品
    关联表单的商品
    拼团和限时购免费商品不能参与打折
    1: 免费:2: 收费:3: 密码支付  4小班课的审核加入
   * 
  */
  _isCanBuyInLive(payType, prodType, relationType) {
    let flag = false;
    if (payType == 2) {
      if (relationType != config.relationTypeMap.collage &&
        prodType != config.ckFrom.activity &&
        prodType != config.ckFrom.booking &&
        prodType != config.ckFrom.circle &&
        prodType != config.ckFrom.edu) {
        flag = true;
      }
    } else if (payType == 4) {
      if (prodType != config.ckFrom.privateClass &&
        relationType != config.relationTypeMap.collage &&
        prodType != config.ckFrom.activity &&
        prodType != config.ckFrom.booking &&
        prodType != config.ckFrom.edu) {
        flag = true;
      }
    } else if (payType == 1 && prodType == config.ckFrom.form) {
      flag = true;
    }
    // if (isHadBuyBind) {
    //   flag = false;
    // }
    console.log("是否可以再直播间内容购买", flag);
    return flag;
  },

  //打开其他商品类型下单
  openOtherPlaceOrder(data) {
    data = (data.detail && data.type && data.currentTarget) ? data.detail : data;
    console.log("openOtherPlaceOrder", data);
    this.exitFullScreen();
    this.setData({
      otherPlaceOrderParams: data
    }, () => {
      if (data.otherParams.fromType == 1 && !(data.otherParams.totalPrice * 1)) {
        this.selectComponent("#otherPlaceOrder").initRewardParams(data);
        this.selectComponent("#otherPlaceOrder").getOrderId();
      } else {
        this.setData({
          isShowOtherPlaceOrder: true
        })
      }

    })
  },

  /*
   *  ┌─────────────────────────────────────────────────────────────┐
   *  @@ 带货跳转相关 end
   *  └─────────────────────────────────────────────────────────────┘
   * 
   */
  /*
   *  ┌─────────────────────────────────────────────────────────────┐
   *  @@ 请求接口 start
   *  └─────────────────────────────────────────────────────────────┘
   * 
   */
  //获取社群消息
  _getSocialInfo() {
    return new Promise((resolve) => {
      let sendData = {};
      if (this._opts.detailId) {
        sendData.detailId = this._opts.detailId
      }
      utils.post(`social/socialRoom/${this._opts.socialRoomId}`, sendData).then((res) => {
        if (!res.isIn) {
          wx.showToast({
            title: '未加入直播间',
            icon: "none",
            duration: 2000,
            success: () => {
              this.redirectToIndex(2000)
            }
          });

        } else if (res.isRemove == 1) {
          wx.showToast({
            title: '你已被移出群聊',
            icon: "none",
            duration: 2000,
            success: () => {
              this.redirectToIndex(2000)
            }
          });
        } else {
          resolve(res);
        }
      })
    })
  },
  //获取直播信息
  _getHLS() {
    return new Promise((resolve) => {
      let url = "";
      let sendData = {}
      if (this._opts.detailId) {
        url = `live/livePersonal/getPlayUrl/${this._opts.liveId}/${this._opts.detailId}`;
        if (this._opts.relateId) {
          sendData.reviewRelateId = this._opts.relateId
        }
      } else {
        url = `liveFlow/getHLSPlayURL/${this._opts.liveId}`
      }
      utils.get(url, sendData).then(res => {
        resolve(res);
      }).catch(() => {
        this.redirectToIndex(2000)
      })
    })
  },
  //获取带货信息
  _getLiveBringGoods() {
    let url = `social/getLiveBringGoods/${this.data.socialRoomId}`;
    let sendData = {};
    if (this.data.moduleType == 1) {
      sendData.detailId = this.data.detailId;
    }
    utils.get(url, sendData).then(res => {
      let totalData = [...res.couponGoods, ...res.normalGoods];
      let info = totalData[0];
      if (!info || info.socialRoomMessageId == 0) return;
      totalData.forEach(item => {
        if (info.socialRoomMessageId * 1 < item.socialRoomMessageId * 1) {
          info = item;
        }
      });
      this.setData({
        commerceFloatInfo: info,
        isShowCommerceFloat: true
      })
    })
  },
  //获取直播简介
  _getLiveDesc() {
    utils.get(`liveFlow/getMobileLiveActivityById/${this.data.liveId}?isSkeleton=1`).then(res => {
      // 删除或无购买被下架
      if (res.data[0].descPath && res.data[0].descPath.length > 5) {
        wx.request({
          url: res.data[0].descPath,
          method: "GET",
          success: (res) => {
            console.log("desc", res.data)
            res.data = res.data.replace(/\<img/gi, '<img style="max-width:100%";height:auto')
            this.setData({
              liveDesc: res.data
            })
          }
        })
      }
    })
  },
  //获取独立直播间间接
  _getPersonalDesc() {
    utils.get('common/prodDetailInfo', {
      prodType: config.ckFrom.personalLive,
      prodId: this.data.liveId
    }, false).then(res => {
      let resData = res[0];
      if (resData.content || resData.content.length > 5) {
        wx.request({
          url: resData.content,
          method: "GET",
          success: (res) => {
            console.log("desc", res.data);
            res.data = res.data.replace(/\<img/gi, '<img style="max-width:100%";height:auto')
            this.setData({
              liveDesc: res.data
            })
          }
        })
      }
    })
  },
  //订阅取消订阅直播
  switchSubscribeLive() {
    let type = this.data.isSubscribeLive == 1 ? 2 : 1;
    utils.post(`liveFlow/setLiveRemind/${this.data.liveId}`, {
      type: type
    }, res => {
      if (res.mpQrcode) {
        this.setData({
          isShowSubscribeQrCode: true,
          subscribeQrCodeUrl: res.mpQrcode
        })
      } else if (res.status) {
        let tipMsg = type == 1 ? '设置成功，直播开始前5分钟进行微信推送提醒哦！' : '已取消提醒';
        wx.showToast({
          title: tipMsg,
        });
        this.setData({
          isSubscribeLive: type == 1 ? 1 : 0
        })
      }
    });
  },
  //获取直播其他配置
  _getLiveRoomOther() {
    let url = '';
    let sendData = {};
    if (this.data.moduleType == 1) {
      url = `liveFlow/getLiveRoomOther/${this.data.liveId}`
    } else {
      url = `live/livePersonal/getLiveRoomOther/${this.data.liveId}`;
      sendData.detailId = this.data.detailId;
    }
    return utils.get(url, sendData).then(res => {
      this.data.otherInfo = res;
      this.setData({
        otherInfo: this.data.otherInfo
      })
    })
  },
  /*
   *  ┌─────────────────────────────────────────────────────────────┐
   *  @@ 请求接口 end
   *  └─────────────────────────────────────────────────────────────┘
   * 
   */
  //查看详情
  liveDescPopupOpen() {
    if (this.data.moduleType == 1 && !this.data.liveDesc) {
      this._getLiveDesc();
    } else if (this.data.moduleType == 2 && !this.data.liveDesc) {
      this._getPersonalDesc();
    }
  },
  // 获取连麦参数pathQuery参数
  getLianMianXcxQuery() {
    let envConfig = utils.getStorage("envConfig");
    console.log("envConfigenvConfig", envConfig)
    let pathQuery = '';
    if (this.data.roles.isNormal) {
      //学员
      if (this.data.moduleType == 1) {
        pathQuery = `/pages/index/index?isStudent=1&liveId=${this.data.liveId}&uId=${this.data.socialInfo.ouId}`;
      } else {
        pathQuery = `/pages/personal/scanCode/index?isStudent=1&liveId=${this.data.liveId}&mt=2&uId=${this.data.socialInfo.ouId}`;
      }
    } else {
      //管理员、嘉宾、讲师
      if (this.data.moduleType == 1) {
        pathQuery = `/pages/index/index?isStudent=0&liveId=${this.data.liveId}`;
      } else {
        pathQuery = `/pages/personal/scanCode/index?isStudent=0&mt=2&liveId=${this.data.liveId}`;
      }
    }
    pathQuery = envConfig.env == 1 ? `${pathQuery}&isTest=1` : envConfig.env == 2 ? `${pathQuery}&isFormal=1` : pathQuery;
    console.log("pathQuery", pathQuery)
    return pathQuery;
  },
  //申请连麦
  applyLianMai() {
    if (this.data.roles.isGuest) {
      //嘉宾一直都有连麦的权限
      this.setData({
        isShowLianMaiQrcodeModal: true
      })
    } else if (this.data.liveInfo.mikeApplyStatus == 2 && !this.data.otherInfo.isVip) {
      //会员连麦，自己是非会员，弹出购买提示
      wx.showModal({
        title: '',
        content: '讲师设置了仅会员可申请连麦，请先开通会员',
        complete: (res) => {
          if (res.confirm) {
            this.openContactGuide({
              prodType: 1,
              socialRoomId: this.data.socialRoomId
            });
          }
        }
      })
    } else {
      if (this.data.liveInfo.joinLiveStatus >= 2) {
        this.setData({
          isShowLianMaiQrcodeModal: true
        })
      } else if (this.data.liveInfo.joinLiveStatus == 1) {
        wx.showToast({
          title: '已提交申请，60秒之内请勿重复提交申请！',
          icon: "none"
        })
      } else {
        wx.showModal({
          title: '',
          content: '确定要申请连麦吗?',
          success: (res) => {
            if (res.confirm) {
              this.setJoinLiveStatus();
            }
          }
        })
      }
    }
  },
  setJoinLiveStatus() {
    utils.post(`appletLiveVideo/setJoinLiveStatus/${this.data.socialRoomId}`, {
      srmId: this.data.socialInfo.srmId,
      status: 1,
      moduleType: this.data.moduleType, //独立直播间
      detailId: this.data.detailId //独立直播间
    }, false).then((res) => {
      this.setData({
        ['liveInfo.joinLiveStatus']: res.status
      });
      wx.showToast({
        title: '已成功提交申请！',
      });
      this._joinLiveStatusResetTimer = setTimeout(() => {
        utils.post(`appletLiveVideo/setJoinLiveStatus/${this.data.socialRoomId}`, {
          srmId: this.data.socialInfo.srmId,
          status: 0,
          moduleType: this.data.moduleType, //独立直播间
          detailId: this.data.detailId //独立直播间
        }, false).then(res => {
          this.setData({
            ['liveInfo.joinLiveStatus']: res.status
          });
        })
      }, 60000)
    })
  },

  //是否初始化播放器 liveType: 0录播 1 手机直播  3 语音直播  4 ppt直播  5 pc直播   6互动直播  7转播
  _getIsNeedInitPlayer(liveInfo = this.liveInfo) {
    let flag = true;
    if (liveInfo.liveType == 3 || liveInfo.liveType == 4) {
      flag = false;
    } else if (liveInfo.status == 0) {
      flag = false;
    } else if (liveInfo.status == 1) {
      if (liveInfo.invalidFlowStatus == -1 || liveInfo.invalidFlowStatus == 0) {
        flag = false;
      }
    } else if (liveInfo.status == 2) {
      if (liveInfo.isResLibraryDel == 1) {
        //视频被素材库删除
        flag = false;
      } else if (liveInfo.isResLibraryDel == 2) {
        //视频被素材库空间不足
        flag = false;
      } else if (liveInfo.liveType == 0) {
        //录播
        if (!liveInfo.playURL && !liveInfo.playURL480p) {
          flag = false;
        }
      } else if (!liveInfo.reviewURL && !liveInfo.reviewURLMp4) {
        //没有回放地址
        if (liveInfo.pushFlow == 0) {
          //没有推流记录
          flag = false;
        } else if (liveInfo.pushFlow == 1) {
          //等待生成回放
          flag = false;
        }
      }
    } else if (liveInfo.status == 3) {
      flag = false;
    } else if (liveInfo.status == 4) {
      flag = false;
    }
    return flag;
  },
  //选中图片
  chooseChatImg() {
    wx.chooseMedia({
      count: 1,
      mediaType: 'image',
      success: (res) => {
        console.log("res", res);
        let resItem = res.tempFiles[0];
        let nameCreate = `xcxlive_${this.data.companyShare.companyId}_${utils.uuid()}.${resItem.tempFilePath.split(".")[1]}`;
        utils.upload({
          filePath: resItem.tempFilePath,
          ispInfo: this._aLiYunISP,
          nameCreate: nameCreate
        }).then(res => {
          this.saveMsgToServer({
            msgType: 2, //消息类型 图片 文字 语音  禁言 禁止语音 拉黑用户
            content: res //消息内容 语音和图片为对应src 文字为文本
          }).then(res => {
            this.setData({
              isShowMore: false
            })
            IM.sendCustomMessage(res);
            this.addLocalChatMsg(res);
          })
        })
      },
    })
  },
  //结束直播
  endLive() {
    console.log("结束直播");
    this.redirectToIndex(0)
  },
  //打开带货弹框
  openCommerceList() {
    if (this.data.roles.isTeacher || this.data.roles.isAdmin) {
      this.setData({
        isShowTeaCommerceList: true
      })
    } else {
      this.setData({
        isShowStuCommerceList: true
      })
    }
  },
  //打开结束直播弹框
  openEndLive() {
    this.setData({
      isShowEndLive: true
    })
  },
  //更新群名片
  updateBusinessCard(e) {
    let val = e.detail;
    console.log(e);
    this.setData({
      ['socialInfo.realName']: val,
      ['socialInfo.nickname']: val
    });
    this._imSendDefaultData.realName = val;
    this._imSendDefaultData.nickname = val;
  },
  //打开群名片弹框
  openBusinessCard() {
    this.setData({
      isShowBusinessCard: true
    })
  },

  //直播详情介绍
  openLiveDescPopup() {
    this.setData({
      isShowLiveDesc: true
    })
  },
  //打开课件图
  openKjtPopup() {
    this.setData({
      isShowChatPopup: true
    }, () => {
      this.setData({
        chatTabIndex: 3
      })
    })
  },
  //显示达人榜
  openTalentRank() {
    this.setData({
      isShowTalentRank: true
    })
  },
  //显示达人榜 榜单
  openTalentRankRoster() {
    this.setData({
      isShowTalentRankRoster: true
    })
  },
  //打开邀请卡
  openInvitionCard() {
    this.setData({
      isShowInvitationCard: true
    })
  },
  //打开刷人次弹框
  openBrushViewCount() {
    this.setData({
      isShowBrushViewCount: true
    })
  },
  //打开地址列表
  openAddrList() {
    this.setData({
      isShowAddressList: true
    })
  },
  //选中收获地址
  chooseAddr(e) {
    let data = e.detail;
    this.setData({
      addressInfo: data
    })
    console.log("data", data)
  },

  delAddr(e) {
    console.log(e);
    let addrId = e.detail;
  },




  // 直播倒计时
  liveTimeDownCount() {
    let liveInfo = this.data.liveInfo;
    let serverTimeTmp = new Date(this.data.socialInfo.currentServerTime.replace(/-/g, '/')).getTime();
    let nowTimeTmp = new Date().getTime();
    let subTmp = nowTimeTmp - serverTimeTmp;
    let startTimeTmp = new Date(liveInfo.startAt.replace(/-/g, '/')).getTime();
    setInterval(() => {
      let nowTmp = new Date().getTime();
      let subTimeTmp = startTimeTmp - nowTmp + subTmp;
      if (subTimeTmp > 0) {
        let timeCount = utils.dtFormat(Math.abs(subTimeTmp), 'dd|hh|mm|ss', {
          isResObj: true
        });
        this.setData({
          liveDownCount: timeCount
        })
      } else {
        this.setData({
          liveDownCount: null
        })
      }

    }, 1000);
  },

  updateLmStatus(e) {
    console.log(e);
    this.setData({
      'liveInfo.joinLiveStatus': e.detail
    })
  },
  //获取敏感词
  _getMsgFilterList() {
    return new Promise(reslove => {
      utils.get('social/getMsgFilterList').then(res => {
        this._sensitiveWord = res;
        this.setData({
          sensitiveWord: res
        });
        reslove();
      }).catch(() => {
        reslove();
      })
    })
  },

  //获取聊天列表
  getChatHistoryList() {
    return new Promise((resolve, reject) => {
      if (this._historySort == 'desc') {
        this.setData({
          isChatListPullDownLoading: true
        })
      } else {
        this.setData({
          isChatListPullUpLoading: true
        })
      }
      let sendData = {
        limit: CHAT_PAGE_SIZE,
        sort: this._historySort,
        page: 1,
        messageId: this._chatScrollMessageId
      }
      if (this.data.moduleType == 2) {
        sendData.detailId = this._opts.detailId;
      }
      utils.get(`social/getHistoryMsg/${this.data.socialRoomId}`, sendData, false).then((res) => {
        let historyChatList = res.msg.data.filter(this._filterAndTransformChat);
        let chatList = [];
        if (this._historySort == 'desc') {
          //降序（上一页）
          this._isChatListPullDownHasMore = res.msg.data.length >= CHAT_PAGE_SIZE ? true : false;
          chatList = historyChatList.concat(this.data.chatList);
          this.setData({
            chatList: chatList
          }, () => {
            this.setData({
              isChatListPullDownLoading: false
            });
            resolve();
          });
        } else {
          //升序（下一页）
          this._isChatListPullUpHasMore = res.msg.data.length >= CHAT_PAGE_SIZE ? true : false;
          chatList = this.data.chatList.concat(historyChatList);
          this.setData({
            chatList: chatList
          }, () => {
            this.setData({
              isChatListPullUpLoading: false
            })
            resolve();
          });
        }
      }).catch(() => {
        if (this._historySort == 'desc') {
          this.setData({
            isChatListPullDownLoading: false
          })
        } else {
          this.setData({
            isChatListPullUpLoading: false
          })
        }
        reject();
      })
    })
  },

  //获取授课区的聊天列表
  getTeaChatHistoryList() {
    return new Promise((resolve, reject) => {
      if (this._teaHistorySort == 'desc') {
        this.setData({
          isTeaChatListPullDownLoading: true
        })
      } else {
        this.setData({
          isTeaChatListPullUpLoading: true
        })
      }
      let sendData = {
        limit: CHAT_PAGE_SIZE,
        sort: this._teaHistorySort,
        lecturer: 1,
        page: 1,
        messageId: this._teaChatScrollMessageId
      }
      if (this.data.moduleType == 2) {
        sendData.detailId = this._opts.detailId;
      }
      utils.get(`social/getHistoryMsg/${this.data.socialRoomId}`, sendData, false).then(res => {
        let historyChatList = res.msg.data.filter(this._filterAndTransformChat);
        let teaChatList = [];
        if (this._teaHistorySort == 'desc') {
          this._isTeaChatListPullDownHasMore = res.msg.data.length >= CHAT_PAGE_SIZE ? true : false;
          //降序（上一页）
          teaChatList = historyChatList.concat(this.data.teaChatList);
          this.setData({
            teaChatList: teaChatList
          }, () => {
            this.setData({
              isTeaChatListPullDownLoading: false
            });
            resolve();
          });
        } else {
          //升序（下一页）
          this._isTeaChatListPullUpHasMore = res.msg.data.length >= CHAT_PAGE_SIZE ? true : false;
          teaChatList = this.data.teaChatList.concat(historyChatList);
          this.setData({
            teaChatList: teaChatList
          }, () => {
            this.setData({
              isTeaChatListPullUpLoading: false
            })
            resolve();
          });
        }
      }, () => {
        reject();
      });
    });
  },

  //过滤item选项
  _filterAndTransformChat(item) {
    let socialInfo = this.data.socialInfo;
    let liveInfo = this.data.liveInfo;
    let roles = this.data.roles;
    let flag = true;
    let tagObj = this._getTags(item.userRole, item.subRole, item.tag);
    let role = utils.getRoles(item.userRole, item.subRole);
    let transformRole = role.isGuest || role.isNormal ? 1 : 2;
    item.tagArr = tagObj.arr;
    item = this.getDynamicName(item);
    item.dynamicName = liveInfo.isHideUserName ? this.hiddenUserName(item.dynamicName, transformRole) : item.dynamicName; //发送者名称
    if (item.msgType == 22 || item.msgType == 73) {
      //打赏现金和实物
      if (socialInfo.showReward == 0) {
        //关闭
        flag = false;
      } else if (socialInfo.showReward == 2) {
        if (roles.isTeacher || roles.isAdmin) {
          flag = true;
        } else if (item.jiguangUserName != socialInfo.jiguangUserName) {
          flag = false;
        }
      }
    } else if (item.msgType == 74 || item.msgType == 75) {
      //已经购买的消息、正在购买的消息（后台开关控制是否显示）
      if (socialInfo.showBuyGoods == 0) {
        //对所有人不可见
        flag = false;
      } else if (socialInfo.showBuyGoods == 2) {
        //对讲师、管理员和购买者可见
        if (roles.isTeacher || roles.isAdmin) {
          flag = true;
        } else if (item.jiguangUserName != socialInfo.jiguangUserName) {
          flag = false;
        }
      }
    } else if (item.msgType == 1) {
      //发送文字
      item.content = this._sensitiveWordFilter(item.content);
    } else if (item.msgType == 3) {
      //独立直播间没有语音ppt直播 所以不记录是否播放的红点，所有的语音一发送就是已读状态
      item.voiceStatus = 1;
    }
    return flag;
  },
  /**
   * 将任意名称转成除第一个字符以外全部替换成* 比如老鹰抓小鸡=>老**
   * @param {昵称} name 
   * @returns 
   */
  hiddenUserName(name = '', role = 1) {
    if (role != 1) {
      return name;
    }
    let str = name.replace(/^(.{3})(.+)/, '$1***');
    return str;
  },


  _sensitiveWordFilter: function (val) {
    if (!val) return '';
    let resStr = val;
    let words = this._sensitiveWord;
    words.forEach((item, index) => {
      let replaceStr = val.replace(/([^u4e00-u9fa5])(\s+)(?=[^u4e00-u9fa5])/g, '$1');
      let regEx = replaceStr.match(new RegExp(words[index], 'g'));
      if (regEx != null) {
        val = replaceStr = replaceStr.replace(new RegExp(words[index], 'g'), '*'.repeat(item.length));
        resStr = replaceStr;
      } else {
        resStr = val;
      }
    });
    return resStr;
  },


  _getTags: function (userRole, subRole, tagStr) {
    //讲师和嘉宾显示的是标签的内容 管理员显示的是管字
    let arr = [];
    let tag = ''; //管理员显示的是管
    if (userRole == 6) {
      //(讲师||嘉宾）&& 管理员
      // arr.push({ userRole: 4, text: '管', className: 'role-admin' });
      if (subRole == 1) {
        //嘉宾+管理员
        arr.push({
          userRole: 2,
          text: tagStr || '管理员/嘉宾',
          className: 'role-guest'
        });
      } else {
        //讲师+管理员
        arr.push({
          userRole: 2,
          text: tagStr || '讲师',
          className: 'role-teacher'
        });
      }
      tag = tagStr;
    } else if (userRole == 4) {
      //管理员
      arr.push({
        userRole: 4,
        text: '管',
        className: 'role-admin'
      });
      tag = '管';
    } else if (userRole == 2) {
      //讲师 || 嘉宾
      if (subRole == 1) {
        arr.push({
          userRole: 2,
          text: tagStr || '嘉宾',
          className: 'role-guest'
        });
      } else {
        arr.push({
          userRole: 2,
          text: tagStr || '讲师',
          className: 'role-teacher'
        });
      }
      tag = tagStr;
    } else {
      tag = tagStr;
    }
    return {
      tag: tag,
      arr: arr
    };
  },


  //获取回放封面
  _getLiveReviewCover(liveInfo) {
    let res = {
      img: '', //图片地址
      intro: ''
    };
    if (liveInfo.liveType != 3 && liveInfo.liveType != 4) {
      if (liveInfo.status == 2) {
        if (liveInfo.isResLibraryDel == 1) {
          //视频被素材库删除
          res.img = 'https://kposshzcdn.ckjr001.com/admin/material/9_material_admin/image/assets/live_source_del.jpg';
          if (liveInfo.playType == 2) {
            res.intro = "回看视频已被管理员删除，"
          }
        } else if (liveInfo.isResLibraryDel == 2) {
          //视频被素材库空间不足
          res.img = 'https://kposshzcdn.ckjr001.com/admin/material/9_material_admin/image/assets/live_source_limit.png';
          if (liveInfo.playType == 2) {
            res.intro = "视频被素材库空间不足"
          }
        } else if (liveInfo.liveType == 0) {
          //录播
          if (!liveInfo.playURL && !liveInfo.playURL480p) {
            res.img = 'https://kposshzcdn.ckjr001.com/admin/material/9_material_admin/image/assets/review_bg.png';
            res.intro = '视频不存在';
          }
        } else if (!liveInfo.reviewURL && !liveInfo.reviewURLMp4) {
          //没有回放地址
          if (liveInfo.pushFlow == 1) {
            //等待生成回放
            res.img = 'https://kposshzcdn.ckjr001.com/admin/material/9_material_admin/image/assets/waitting.png';
            if (liveInfo.playType == 2) {
              res.intro = "正在生成回看，预计5分钟内生成"
            }
          } else {
            //没有推流记录
            res.img = 'https://kposshzcdn.ckjr001.com/admin/material/9_material_admin/image/assets/push-none.png';
            if (liveInfo.playType == 2) {
              res.intro = "当前没有推流记录"
            }
          }
        }
      } else if (liveInfo.status == 3) {
        //不支持回放
        res.img = 'https://kposshzcdn.ckjr001.com/admin/material/9_material_admin/image/assets/review_bg.png';
        res.intro = '直播已结束';
      } else if (liveInfo.status == 4) {
        res.img = 'https://kposshzcdn.ckjr001.com/admin/material/9_material_admin/image/assets/review_bg.png';
        res.intro = '回放已过期';
      }
    }
    return res;
  },


  exitFullScreen() {
    if (this.data.isVideoFullScreen) {
      this._videoCtx.exitFullScreen()
    }
    if (this.data.isPlayerFullScreen) {
      this._playerCtx.exitFullScreen();
    }
  },
  /*
   *  ┌─────────────────────────────────────────────────────────────┐
   *  @ live-player 直播中方法-start
   *  └─────────────────────────────────────────────────────────────┘
   * 
   */
  //清晰度选择
  playerModeChoose(e) {
    console.log(e)
    let dataset = e.currentTarget.dataset;
    if (dataset.index == this.data.playerModeIndex) return;
    this.setData({
      playerModeIndex: dataset.index,
      isShowPlayerModeList: false
    })
  },
  //清晰度弹窗显示
  playerModeListShow() {
    this.setData({
      isShowPlayerModeList: true
    })
  },
  //全屏变化
  playerFullscreenChange(e) {
    let detail = e.detail; //{fullScreen:"",direction:""}
    this.setData({
      isShowStuCommerceList: false,
      isShowTeaCommerceList: false,
      isPlayerFullScreen: detail.fullScreen
    })
  },
  //播放
  playerPlay() {
    this._playerCtx.play({
      success: () => {
        this.setData({
          playerStatus: 1
        })
      }
    });
  },
  //暂停
  playerStop() {
    this._playerCtx.stop({
      success: () => {
        this.setData({
          playerStatus: 0
        })
      }
    });
  },
  //恢复
  playerResume() {
    this._playerCtx.resume();
  },
  playerToggleFullScreen() {
    if (this.data.isPlayerFullScreen) {
      this._playerCtx.exitFullScreen();
    } else {
      this._playerCtx.requestFullScreen({
        direction: 90
      })
    }
  },
  playerStateChange(e) {
    console.log("playerStateChange", e);
    let code = e.detail.code;
    let playerStatus = this.data.playerStatus;
    switch (code) {
      case 2001:
        // playerStatus = -1;
        break;
      case 2004:
        playerStatus = 1;
        this._startLiveTimeCount();
        break;
    }
    this.setData({
      playerStatus: playerStatus
    })
  },
  playerEnterPictureInPicture(e) {
    console.log("playerEnterPictureInPicture", e)
  },
  playerLeavePictureInPicture() {
    console.log("playerLeavePictureInPicture", e)
  },
  playerNetStatus(e) {
    // console.log("playerNetStatus", e)
  },
  playerRefresh() {
    this._playerCtx.stop();
    this._playerCtx.play();
  },
  //错误回调
  playerError(e) {
    console.log("playerError", e)
  },
  tapPlayer() {
    let isShowToolBar = this.data.isShowToolBar;
    let isClearScreenOther = this.data.isClearScreenOther;
    if (this.data.liveInfo.playType == 2) {
      //竖屏
      if (isShowToolBar) {
        //当前播放器进度条显示
        isClearScreenOther = false;
      } else {
        isClearScreenOther = true;
      }
    } else {
      if (this.data.isPlayerFullScreen) {
        if (isShowToolBar) {
          //当前播放器进度条显示
          isClearScreenOther = true;
        } else {
          isClearScreenOther = false;
        }
      }
    }
    this.setData({
      isShowToolBar: !isShowToolBar,
      isClearScreenOther: isClearScreenOther
    })
  },

  /*
   *  ┌─────────────────────────────────────────────────────────────┐
   *  @ live-player 直播中方法-end
   *  └─────────────────────────────────────────────────────────────┘
   * 
   */


  /*
   *  ┌─────────────────────────────────────────────────────────────┐
   *  @  video 回放方法-start
   *  └─────────────────────────────────────────────────────────────┘
   * 
   */
  //倍数播放
  videoPlaybackRate() {
    this.data.playbackRateIndex++;
    if (this.data.playbackRateIndex > 4) {
      this.data.playbackRateIndex = 0;
    }
    this.setData({
      playbackRateIndex: this.data.playbackRateIndex
    })
    this._videoCtx.playbackRate(this.data.playbackRate[this.data.playbackRateIndex])
  },
  //线路选择
  videoSourceChoose(e) {
    let dataset = e.currentTarget.dataset;
    if (dataset.index == this.data.videoSourceIndex) return;
    this._videoSeekTime = this._videoCurrentTime;
    this.setData({
      videoSourceIndex: dataset.index,
      isShowVideoSourceList: false
    }, () => {
      this._videoCtx.play()
    });

  },
  //线路弹窗显示
  videoSourceListShow() {
    this.setData({
      isShowVideoSourceList: true
    })
  },

  videoToggleFullScreen() {
    if (this.data.isVideoFullScreen) {
      this._videoCtx.exitFullScreen()
    } else {
      this._videoCtx.requestFullScreen({
        direction: 90
      })
    }
  },
  videoRefresh() {
    this._videoSeekTime = this._videoCurrentTime;
    this._videoCtx.stop();
    this._videoCtx.seek(this._videoSeekTime);
    this._videoCtx.play();

  },
  videoReStart() {
    this._videoCtx.seek(0);
    this._videoCtx.stop();
    this._videoCtx.play();
  },
  //全屏的变化
  videoFullScreenChange(e) {
    console.log("videoFullScreenChange", e);
    let detail = e.detail; //{fullScreen:"",direction:""}
    this.setData({
      isShowStuCommerceList: false,
      isShowTeaCommerceList: false,
      isVideoFullScreen: detail.fullScreen
    });
    setTimeout(() => {
      this._getElemClientRect("#J_progress-holder").then(res => {
        this._progressHolderRect = res;
      });
    }, 1500);
  },
  videoPause() {
    this._videoCtx.pause();
  },
  videoPlay() {
    this._videoCtx.play();
  },
  videoBackgroundPlayback() {
    this._videoCtx.requestBackgroundPlayback();
  },
  //加载进度变化时触发
  videoProgress(e) {
    // console.log("videoProgress", e);
    this.setData({
      videoStatus: 1
    })
  },
  videoWaiting(e) {
    console.log("videoWaiting", e);
    this.setData({
      videoStatus: 2
    })
  },
  //seek 完成时触发
  videoSeekComplete(e) {
    console.log("videoSeekComplete", e)
    if (this._isProgressTouching == true && this._videoSeekTime) {
      this.videoPlay();
      this._recordMemoryTime(this._videoSeekTime);
      this._isProgressTouching = false;
      this._videoSeekTime = 0;
    }
  },
  //播放器进入小窗
  videoEnterPictureInPicture(e) {
    console.log("videoEnterPictureInPicture", e)
  },
  //播放器退出小窗
  videoLeavePictureInPicture(e) {
    console.log("videoLeavePictureInPicture", e)
  },
  //视频元数据加载完成时触发
  videoLoadedMetaData(e) {
    console.log("videoLoadedMetaData", e);
    this._videoDuration = Math.ceil(e.detail.duration);
    this.setData({
      videoTotalTime: this._transformVideoTime(Math.ceil(e.detail.duration))
    });
    if (this.data.liveInfo.playHistoryTime) {
      console.log('设置记忆播放点：', Math.abs(this.data.liveInfo.playHistoryTime));
      this._videoCtx.seek(this.data.liveInfo.playHistoryTime);
    }
  },
  //播放进度变化时触发
  videoTimeUpdate(e) {
    this._videoCurrentTime = Math.ceil(e.detail.currentTime);
    utils.requestAniFrame(() => {
      this.setData({
        videoCurrentTime: this._transformVideoTime(Math.floor(e.detail.currentTime)),
        videoProgressPercent: e.detail.currentTime / this._videoDuration
      });
    })
    //回放记忆播放
    if (!this._videoTimeUpdateTimer) {
      this._videoTimeUpdateTimer = setTimeout(() => {
        if (!this._videoCtx) return;
        this._recordMemoryTime(this._videoCurrentTime);
        this._videoTimeUpdateTimer = null;
      }, RECORD_DISTANCE_TIME * 1000);
    }
  },
  //当开始/继续播放时触发
  videoPlayCB(e) {
    console.log("videoPlayCB", e, this._videoSeekTime);
    this.setData({
      videoStatus: 1
    });
    this._startLiveTimeCount();
  },
  //当暂停播放时触发 pause 事件
  videoPauseCB(e) {
    console.log("videoPauseCB", e)
    this.setData({
      videoStatus: 0
    });
    // this._stopLiveTimeCount();
  },
  //
  videoEnd(e) {
    console.log("videoEnd", e);
    //统计观看时长
    this.recordWatchCount();
    //播放记忆
    this._recordMemoryTime(0, 1);
    this._videoSeekTime = 0;
    this._videoCtx.pause();
    this.setData({
      videoStatus: 3,
      videoCurrentTime: this._transformVideoTime(this._videoDuration),
      'liveInfo.playHistoryIsFinish': 1,
      'liveInfo.playHistoryTime': 0
    });
  },
  videoError(e) {
    console.log("videoError", e)
  },

  videoProgressTap(e) {
    console.log("videoProgressTap", e, this._progressHolderRect)
    if (!this._isAllowDragProgressBar || !this._progressHolderRect.width) return;
    this._isProgressTouching = true;
    this.videoPause();
    let evt = e.changedTouches[0];
    const position = evt.pageX - this._progressHolderRect.left;
    this._setVideoPosition(position);
    this._videoSeekTime = this._getVideoSeekTime(position);
    this._videoCtx.seek(this._videoSeekTime);
  },

  videoProgressTouchstart(e) {
    if (!this._isAllowDragProgressBar || !this._progressHolderRect.width) return;
    this.videoPause();
    this._isProgressTouching = true;
  },
  videoProgressTouchmove(e) {
    if (!this._isAllowDragProgressBar || !this._progressHolderRect.width) return;
    let evt = e.changedTouches[0];
    const position = evt.pageX - this._progressHolderRect.left;
    this._videoSeekTime = this._getVideoSeekTime(position);
    utils.requestAniFrame(() => {
      this._setVideoPosition(position);
    })

  },
  videoProgressTouchend(e) {
    if (!this._isAllowDragProgressBar || !this._progressHolderRect.width) return;
    utils.requestAniFrame(() => {
      this._videoCtx.seek(this._videoSeekTime);
    });

  },
  videoProgressTouchcancel(e) {
    if (!this._isAllowDragProgressBar || !this._progressHolderRect.width) return;
    this._isProgressTouching = false;
    this.videoPlay();
  },


  _getVideoSeekTime(position) {
    position = position > this._progressHolderRect.width ? this._progressHolderRect.width : position;
    return Math.floor(position / this._progressHolderRect.width * this._videoDuration);
  },
  _setVideoPosition(val) {
    if (val < 0 || val > this._progressHolderRect.width) return;
    this.setData({
      videoProgressPercent: val / this._progressHolderRect.width
    })
  },
  _startLiveTimeCount() {
    clearTimeout(this._liveWatchTimeCountTimer);
    let companyShare = this.data.companyShare;
    this._liveWatchTimeCount++;
    if (this._liveWatchTimeCount > RECORD_DISTANCE_TIME && !this._recordWatchCountTimer) {
      this.recordWatchCount();
    }
    //领取积分开启(enableWatchLiveFlowPoint)
    if (companyShare.companyAuth.enableWatchLiveFlowPoint == 1 || companyShare.companyAuth.enableWatchLiveFlow == 1) {
      this._liveGetPointTimeCount++;
      if (companyShare.companyAuth.pointModel == 2 && this._liveGetPointTimeCount > 5 && !this._isFinshGetPoint && !this._isGetPointRequesting) {
        //自动获取积分记录
        this._isGetPointRequesting = true;
        this.getWatchIntegration(61, this._liveGetPointTimeCount)
          .then(() => {
            this._isGetPointRequesting = false;
            this._isFinshGetPoint = true;
          })
          .catch(() => {
            this._isGetPointRequesting = false;
            this._isFinshGetPoint = false;
          });
      }
      // console.log('this._liveGetPointTimeCount', this._liveGetPointTimeCount);
    }

    // console.log('this._liveWatchTimeCount', this._liveWatchTimeCount);
    this._liveWatchTimeCountTimer = setTimeout(this._startLiveTimeCount, 1000);
  },
  welfareRecordWatchCount(e) {
    console.log("e", e);
    if (e.detail) {
      let time = e.detail * 1;
      this._liveWatchTimeCount += time;
      this.recordWatchCount();
    } else {
      this.recordWatchCount();
    }
  },
  //记录观看
  recordWatchCount(count = this._liveWatchTimeCount || 1) {
    return new Promise((resolve, reject) => {
      if (!this._recordWatchCountTimer) {
        let data = {
          userId: this.data.userId,
          status: this.data.liveInfo.status,
          curPlayTime: 1, //先传1
          watchTime: count * 1000
        };
        let url = "";
        if (this.data.moduleType == 1) {
          url = `social/cacheWatchTime/${this.data.socialRoomId}`;
        } else {
          url = `live/livePersonal/cacheWatchTime/${this.data.liveId}`;
          data.detailId = this.data.detailId;
        }
        this._recordWatchCountTimer = setTimeout(() => {
          utils.post(url, data, false).then(() => {
            console.log('直播观看时长上报成功！', data);
            this._liveWatchTimeCount = 0;
            this._recordWatchCountTimer = null;
            resolve();
          }).catch(() => {
            this._recordWatchCountTimer = null;
            reject();
          })
        }, 1000);
      } else {
        resolve();
      }
    });
  },
  //记录播放记忆
  _recordMemoryTime(time, isFinsh = 0) {
    return new Promise((resolve, reject) => {
      if (!this._recordMemoryTimer) {
        this._recordMemoryTimer = setTimeout(() => {
          let url = '';
          let sendData = {};
          if (this.data.moduleType == 1) {
            url = `liveFlow/insertLiveVideoPlayRecord/${this.data.liveId}/${time}`;
            sendData = {
              isFinish: isFinsh
            }
          } else {
            url = `live/livePersonal/saveWatchPlayRecord/${this.data.liveId}/${this.data.detailId}`;
            sendData = {
              playTime: time,
              isFinsh: isFinsh
            }
          }
          utils.post(url, sendData, false).then(() => {
            console.log('记忆播放上报成功！', isFinsh ? '观看完成,记忆点在：' + time : '观看或拖动了：' + Math.abs(time - this.data.liveInfo.playHistoryTime) + ',记忆点在' + time);
            this._recordMemoryTimer = null;
            this.setData({
              ['liveInfo.playHistoryTime']: time
            })
            resolve();
          }).catch(() => {
            this._recordMemoryTimer = null;
            reject();
          })
        }, 250);
      } else {
        resolve();
      }
    });
  },
  _stopLiveTimeCount() {
    clearTimeout(this._liveWatchTimeCountTimer);
    this._liveWatchTimeCountTimer = null;
  },
  /**
   * @description:领取积分
   * @param {type} 54：观看直播每分钟,60分钟后不再累计   61：观看直播（次数）观看直播获得积分(每有效收听一次)相当于每次点击播放按钮 每日达标
   * @return {time} 时间
   */
  getWatchIntegration(type, time = this._liveGetPointTimeCount) {
    return new Promise((resolve, reject) => {
      let sendData = {
        cId: -1,
        extId: this.data.liveId,
        pointFrom: type,
        duration: type == 54 ? Math.floor(time / 60) : time
      };
      if (type == 54 && this._liveGetPointTimeCount < 60) {
        wx.showToast({
          title: '请先观看直播至少一分钟，再领取' + this.data.companyShare.companyAuth.integrateName1,
          icon: "none"
        })
        return;
      }
      utils.post('common/getPoints', sendData, false).then(res => {
        let status = res.points.status;
        if (type == 54) {
          if (status == 1) {
            if (res.points.points != 0) {
              this.setData({
                integrateCount: res.points.points,
                showIntegrate: true
              })
              this._setPointStorage();
            }
            this.isShowGetPoints = false;
          } else {
            let introTxt = '';
            if (status == -1) {
              introTxt = '请先观看直播至少一分钟，再领取';
            } else if (status == -2) {
              introTxt = '您已领过';
              this.isShowGetPoints = false;
              this._setPointStorage();
            } else {
              introTxt = '领取失败';
            }
            wx.showToast({
              title: introTxt + this.companyAuth.integrateName1,
            })
          }
        }
        resolve();
      }).catch(() => {
        reject();
      })
    });
  },
  _setPointStorage() {
    // 成功领取积分后缓存记录当前聊天室id
    let curRoomId = socialRoomId * 1;
    let localIntArr = utils.getStorage('liveIntArr');
    let intArr = (localIntArr && JSON.parse(localIntArr)) || [];
    if (!(localIntArr && JSON.parse(localIntArr).includes(curRoomId))) {
      intArr.length < 99999 ? intArr.push(curRoomId) : intArr.shift();
      utils.setStorage('liveIntArr', JSON.stringify(intArr));
    }
  },
  _transformVideoTime(time) {
    const SECOND = 1;
    const MINUTE = 1 * 60 * SECOND;
    const HOURS = 1 * 60 * MINUTE;
    let hour = 0;
    let minute = 0;
    let second = 0;
    let resStr = '';
    hour = Math.floor(time / HOURS);
    minute = Math.floor((time - hour * HOURS) / MINUTE);
    second = Math.floor(time - hour * HOURS - minute * MINUTE);
    minute = minute > 9 ? minute : ('0' + minute);
    second = second > 9 ? second : ('0' + second);
    resStr = minute + ':' + second;
    if (hour) {
      resStr = hour + ':' + resStr;
    }

    return resStr;
  },
  //点击视频
  tapVideo() {
    let isShowToolBar = this.data.isShowToolBar;
    let isClearScreenOther = this.data.isClearScreenOther;
    if (this.data.liveInfo.playType == 2) {
      //竖屏
      if (isShowToolBar) {
        //当前播放器进度条显示
        isClearScreenOther = false;
      } else {
        isClearScreenOther = true;
      }
    } else {
      if (this.data.isPlayerFullScreen) {
        if (isShowToolBar) {
          //当前播放器进度条显示
          isClearScreenOther = true;
        } else {
          isClearScreenOther = false;
        }
      }
    }
    this.setData({
      isShowToolBar: !isShowToolBar,
      isClearScreenOther: isClearScreenOther
    })
  },

  openAirPlay() {
    // const query = wx.createSelectorQuery().in(this);
    // query.select("#test1");
    // query.exec(function(res){
    //   console.log(res);
    // })

    // if (window.WebKitPlaybackTargetAvailabilityEvent) {
    //   this._Player.children_[0].webkitShowPlaybackTargetPicker();
    // } else {
    //   this.$vux.toast.show({
    //     text: '您的设备不支持投屏！',
    //     type: 'warn',
    //     time: 3000
    //   });
    // }
  },
  /*
   *  ┌─────────────────────────────────────────────────────────────┐
   *  @  video 回放方法-end
   *  └─────────────────────────────────────────────────────────────┘
   * 
   */


  //发送聊天
  onSendChatText(e) {
    console.log(e);
    let text = e.detail.value.replace(/(^\s*)|(\s*$)/g, "");
    if (text === '') return;
    let msgContent = {
      msgType: 1,
      content: text
    };
    this.setData({
      chatInputVal: '',
    });
    this.saveMsgToServer(msgContent).then(res => {
      if (this.data.moduleType == 2 && this.data.liveInfo.status >= 2) {
        this.addLocalChatMsg(res);
      } else {
        IM.sendCustomMessage(res);
        this.addLocalChatMsg(res);
      }
    })
  },
  //保存后端
  saveMsgToServer(data) {
    return new Promise((resolve, reject) => {
      let msgData = {
        ...this._imSendDefaultData,
        ...data
      };
      utils.post(`social/sendCustMsg/${this.data.socialRoomId}`, msgData, false).then(res => {
        if (res.socialRoomMessageId == -1) {
          wx.showToast({
            title: '已被禁言'
          })
          return;
        } else {
          msgData.socialRoomMessageId = res.socialRoomMessageId;
          msgData.createdAt = res.createdAt;
          msgData.content = res.content || data.content;
          msgData.tagArr = this._tags.arr;
          resolve(msgData)
        }
      })
    })
  },
  //添加到本地
  addLocalChatMsg(data) {
    //发送带货
    let roles = this.data.roles;
    let liveInfo = this.data.liveInfo;
    if (data.msgType == 70) {
      // 刚发送的带货消息没有经后台转换成payType，需要自己加
      data.payType = data.voiceDuration;
      this.setData({
        commerceFloatInfo: data
      })
    } else if (data.msgType == 1) {
      data.content = this._sensitiveWordFilter(data.content);
    }
    data = this.getDynamicName(data);
    if (liveInfo.isHideUserName) {
      data.dynamicName = this.hiddenUserName(data.dynamicName, (roles.isGuest || roles.isNormal) ? 1 : 2)
    }
    console.log("this._isChatListPullUpHasMore", this._isChatListPullUpHasMore)
    //讨论区
    if (this._isChatListPullUpHasMore) {
      this._historySort = "desc";
      this._chatScrollMessageId = 0;
      this.getChatHistoryList().then(() => {
        this._isChatListPullUpHasMore = false;
        this.dmScrollToBottom();
        this.chatScrollToBottom();

      })
    } else {
      this.data.chatList.push(data)
      this.setData({
        chatList: this.data.chatList
      }, () => {
        this.dmScrollToBottom();
        this.chatScrollToBottom();
      })
    }
    //授课区
    if (roles.isTeacher || roles.isAdmin) {
      if (this._isTeaChatListPullUpHasMore) {
        this._teaHistorySort = "desc";
        this._teaChatScrollMessageId = 0;
        this.getTeaChatHistoryList().then(() => {
          this._isTeaChatListPullUpHasMore = false;
          this.teaScrollToBottom();
        })
      } else {
        this.data.teaChatList.push(data)
        this.setData({
          teaChatList: this.data.teaChatList
        }, () => {
          this.teaScrollToBottom();
        })
      }
    }
  },


  /**
   * @description:获取dynamicName（依赖注入）
   * @param {Array} teacherAndAdminKey  讲师和管理员的jiguangUserName集合
   */
  getDynamicName(data, roles = this.data.roles, isShowRealName = this.data.liveInfo.isShowRealName) {
    if (Object.prototype.toString.call(data) == '[object Object]') {
      if (roles.isAdmin || roles.isTeacher) {
        if (isShowRealName) {
          data.dynamicName = data.userRealName || data.realName || data.userName;
        } else {
          data.dynamicName = data.realName || data.userName;
        }
      } else {
        data.dynamicName = data.realName || data.userName;
      }
    }
    return data;
  },

  /*
   *  ┌─────────────────────────────────────────────────────────────┐
   *  @@ 聊天区域 start
   *  └─────────────────────────────────────────────────────────────┘
   * 
   */
  // 弹幕滚动到底部
  dmScrollToBottom() {
    this.setData({
      dmScrollTop: 9999999999999
    }, () => {
      this.chatListAscCutOff();
    });
  },
  // 讨论区滚动到底部
  chatScrollToBottom() {
    this.setData({
      chatScrollTop: 9999999999999
    }, () => {
      this.chatListAscCutOff();
    })
  },
  // 授课区滚动到底部
  teaScrollToBottom() {
    this.setData({
      teaScrollTop: 9999999999999
    }, () => {
      this.teaListAscCutOff();
    })
  },
  //讨论区数据截断
  chatListAscCutOff() {
    if (this.data.chatList.length > SHOW_MSG_LIMIT) {
      this.setData({
        chatList: this.data.chatList.slice(this.data.chatList.length - SHOW_MSG_LIMIT)
      })
      this._isChatListPullDownHasMore = true;
    }
  },
  //授课区数据截断
  teaListAscCutOff() {
    if (this.data.teaChatList.length > SHOW_MSG_LIMIT) {
      this.setData({
        teaChatList: this.data.teaChatList.slice(this.data.teaChatList.length - SHOW_MSG_LIMIT)
      })
      this._isTeaChatListPullDownHasMore = true;
    }
  },
  //弹幕列表
  dmScrollListern(e) {
    this._dmScrollEventDetail = e.detail;
    this._isDmScrollAtBottom = Math.floor(e.detail.scrollHeight - e.detail.scrollTop - this._dmScrollViewRect.height) <= 10 ? true : false;
    if (!this._isChatListPullUpHasMore && (this._isDmScrollAtBottom || this._isChatScrollAtBottom)) {
      this.setData({
        newMsgStack: []
      })
    }
  },
  //聊天列表
  chatScrollListern(e) {
    this._chatScrollEventDetail = e.detail;
    this._isChatScrollAtBottom = Math.floor(e.detail.scrollHeight - e.detail.scrollTop - this._chatScrollViewRect.height) <= 10 ? true : false;
    if (!this._isChatListPullUpHasMore && (this._isDmScrollAtBottom || this._isChatScrollAtBottom)) {
      this.setData({
        newMsgStack: []
      })
    }
  },
  //授课列表
  teaScrollListern(e) {
    this._teaScrollEventDetail = e.detail;
    this._isTeaScrollAtBottom = Math.floor(e.detail.scrollHeight - e.detail.scrollTop - this._chatScrollViewRect.height) <= 10 ? true : false;
  },

  //下一页
  chatNextPage() {
    console.log("chatNextPage");
  },

  //上一页
  chatPrevPage(e) {
    console.log("chatPrevPage", e, this._isChatListPullDownRequesting, this._isChatListPullDownHasMore)
    if (this._isChatListPullDownRequesting || !this._isChatListPullDownHasMore) return;
    let item = this.data.chatList.find(item => !!item.socialRoomMessageId && item.isRead);
    console.log("chatPrevPage", item)
    if (!item) return;

    this._isChatListPullDownRequesting = true;
    this._chatScrollMessageId = item.socialRoomMessageId;
    this._historySort = 'desc';
    let isChatScrollElem = e.currentTarget.id == "J_chat-scroll";
    let dmScrollHeight = this._dmScrollEventDetail.scrollHeight;
    let chatScrollHeight = 0;
    if (isChatScrollElem) {
      chatScrollHeight = this._chatScrollEventDetail.scrollHeight;
    }
    this.getChatHistoryList().then(() => {
      this._isChatListPullDownRequesting = false;
      //弹幕区域
      this._getElemClientRect("#J_dm-chatist").then(res => {
        this._dmChatListRect = res;
        this.setData({
          dmScrollTop: res.height - dmScrollHeight
        })
      })
      if (isChatScrollElem) {
        //讨论区
        this._getElemClientRect("#J_chatList").then(res => {
          console.log("res11", res, chatScrollHeight)
          this._chatListRect = res;
          this.setData({
            chatScrollTop: res.height - chatScrollHeight
          })
        })
      }
    }).catch(() => {
      this._isChatListPullDownRequesting = false;
    });
  },

  //上一页
  teaPrevPage(e) {
    console.log("teaPrevPage", e, this._isTeaChatListPullDownRequesting, this._isTeaChatListPullDownHasMore)
    if (this._isTeaChatListPullDownRequesting || !this._isTeaChatListPullDownHasMore) return;
    let item = this.data.teaChatList.find(item => !!item.socialRoomMessageId && item.isRead);
    console.log("teaPrevPage", item)
    if (!item) return;
    this._isTeaChatListPullDownRequesting = true;
    this._teaChatScrollMessageId = item.socialRoomMessageId;
    this._teaHistorySort = 'desc';
    let teaScrollHeight = this._teaScrollEventDetail.scrollHeight;
    this.getTeaChatHistoryList().then(() => {
      this._isTeaChatListPullDownRequesting = false;
      this._getElemClientRect("#J_teaList").then(res => {
        this._teaListRect = res;
        this.setData({
          teaScrollTop: res.height - teaScrollHeight
        })
      })
    }).catch(() => {
      this._isTeaChatListPullDownRequesting = false;
    });
  },
  //滚动到最新消息
  chatScrollToNewMsg() {
    if (!this._isChatListPullUpHasMore) {
      this.dmScrollToBottom();
      this.chatScrollToBottom();
      this.setData({
        newMsgStack: []
      })
    } else {
      this._historySort = "desc";
      this._chatScrollMessageId = 0;
      this.getChatHistoryList().then(() => {
        this._isChatListPullUpHasMore = false;
        this.dmScrollToBottom();
        this.chatScrollToBottom();
        this.setData({
          newMsgStack: []
        })
      })
    }
  },
  previewKjtImg(e) {
    console.log(e.currentTarget.dataset);
    let url = e.currentTarget.dataset.url;
    let urls = [];
    if (!Array.isArray(this.data.liveInfo.material) || !this.data.liveInfo.material.length) {
      urls = [url];
    } else {
      this.data.liveInfo.material.forEach(item => {
        urls.push(item.url)
      })
    }
    console.log(urls)
    wx.previewImage({
      current: url,
      urls: urls,
    })
  },
  openChatPopup() {
    console.log(this.data.teaScrollTop)
    this.setData({
      isShowChatPopup: true
    }, () => {
      this.setData({
        chatTabIndex: 1
      })
    })
  },

  chatPopupOpen() {
    setTimeout(() => {
      this.teaScrollToBottom();
    }, 250)
    this._getElemClientRect("#J_tea-scroll").then((res) => {
      console.log("res", res);
      this._chatScrollViewRect = res;
    })
  },
  chatPopupClose() {
    this._teaScrollEventDetail = null;
    this._chatScrollEventDetail = null;
  },

  openTeaLuckyDraw() {
    this.setData({
      isShowMore: false
    })
    this.selectComponent("#luckyDrawTea").showList();
  },


  _getElemClientRect(str) {
    return new Promise((reslove) => {
      const query = this.createSelectorQuery();
      query.select(str).boundingClientRect();
      query.exec((res) => {
        console.log("元素：" + str, res);
        reslove(res[0]);
      })
    })
  },
  /*
   *  ┌─────────────────────────────────────────────────────────────┐
   *  @ 聊天区域 end
   *  └─────────────────────────────────────────────────────────────┘
   * 
   */
  chatTabChange(e) {
    console.log(e);
    let val = e.currentTarget.dataset.val;
    if (val == this.data.chatTabIndex) return;
    this.setData({
      chatTabIndex: val
    }, () => {
      if (val == 1 && !this._teaScrollEventDetail) {
        this.teaScrollToBottom();
      }
      if (val == 2 && !this._chatScrollEventDetail) {
        this.chatScrollToBottom();
      }
    })
  },

  // 打开更多设置
  openMorePopup() {
    this.setData({
      isShowMore: true
    })
  },


  /*
   *  ┌─────────────────────────────────────────────────────────────┐
   *  @ 授课区域 start
   *  └─────────────────────────────────────────────────────────────┘
   * 
   */
  //授课区
  redirectToIndex(time) {
    setTimeout(() => {
      wx.redirectTo({
        url: "/pages/index/index"
      })
    }, time)
  },

  /*
   *  ┌─────────────────────────────────────────────────────────────┐
   *  @ 授课区域 start
   *  └─────────────────────────────────────────────────────────────┘
   * 
   */

  _handlerIMMessage(data) {
    if (this.data.moduleType == 2 && this.data.liveInfo.status >= 2) return; //直播间回放不接收消息
    let liveInfo = this.data.liveInfo,
      socialInfo = this.data.socialInfo,
      roles = this.data.roles,
      msgRoles = utils.getRoles(data.userRole, data.subRole);
    data.msgType = data.msgType * 1;

    if (CHAT_LIST_MSG_TYPE.includes(data.msgType)) {
      let tagObj = this._getTags(data.userRole, data.subRole, data.tag),
        //消息默认都要推入到chatList(有些消息是有开关限制的)
        isAddToChatList = true,
        //消息根据角色和talkType来确认是否推入teacherChatList
        isAddToTeacherChatList = (msgRoles.isAdmin || msgRoles.isTeacher) && data.talkType == 1 ? true : false;
      data.tagArr = tagObj.arr;
      data = this.getDynamicName(data);
      data.dynamicName = liveInfo.isHideUserName ? this.hiddenUserName(data.dynamicName, (msgRoles.isGuest || msgRoles.isNormal) ? 1 : 2) : data.dynamicName; //发送
      if (data.msgType == 1 || data.msgType == 18 || data.msgType == 19) {
        data.content = this._sensitiveWordFilter(data.content);
      } else if (data.msgType == 11) {
        //群禁言
        isAddToTeacherChatList = false;
        this.setData({
          'socialInfo.memberPrivileges': data.content
        });
        this._setGroupTaboo(data.content);
      } else if (data.msgType == 13) {
        //个人禁言
        if (data.content.jiguangUserName == socialInfo.jiguangUserName) {
          //自己被禁言
          this.setData({
            isSelfTaboo: true
          }, () => {
            this._setInputObj();
          });
        }
      } else if (data.msgType == 14) {
        //个人解除禁言
        if (data.content.jiguangUserName == socialInfo.jiguangUserName) {
          this.setData({
            isSelfTaboo: false
          }, () => {
            this._setInputObj();
          });
        }
      } else if (data.msgType == 16) {
        let filterChatList = this.data.chatList.filter(item => {
          return item.socialRoomMessageId != data.socialRoomMessageId;
        });
        let filterTeacherList = this.data.teaChatList.filter(item => {
          return item.socialRoomMessageId != data.socialRoomMessageId;
        });
        this.setData({
          chatList: filterChatList,
          teaChatList: filterTeacherList
        });
        if (msgRoles.isAdmin || msgRoles.isTeacher) {
          isAddToTeacherChatList = true;
        }
        //带货列表弹框显示刷新
        if (this.selectComponent("#J_commerce-stu").data.isShow) {
          this.selectComponent("#J_commerce-stu").refreshData();
        }
        //带货浮窗
        if (this.data.commerceFloatInfo.socialRoomMessageId == data.socialRoomMessageId) {
          this.setData({
            isShowCommerceFloat: false
          })
        } else if (this.data.commerceFloatCouponInfo.socialRoomMessageId == data.socialRoomMessageId) {
          this.setData({
            isShowCommerceCouponFloat: false
          })
        }
      } else if (data.msgType == 24) {
        //结束直播
        this._stopLiveTimeCount();
        this.recordWatchCount();

        //弹框
        wx.showModal({
          title: '提示',
          content: '当前直播已结束啦！',
          showCancel: false,
          success: (res) => {
            if (res.confirm) {
              this.redirectToIndex(0)
            }
          }
        })
      } else if (data.msgType == 64) {
        //加入黑名单移除群聊
        if (data.jiguangUserName == socialInfo.jiguangUserName) {
          wx.showToast({
            title: '你已被移出群聊',
            icon: 'none',
            duration: 2500,
            success: () => {
              this.redirectToIndex(2500)
            }
          })
        }
      } else if (data.msgType == 66) {

      } else if (data.msgType == 70) {
        //带货消息 (ios app 发送vipinfo为字符串，需要特殊处理)
        if (data.vipInfo && typeof data.vipInfo === 'string') {
          data.vipInfo = JSON.parse(msgData.vipInfo);
        }
        if (!data.version) {
          let payTypeMao = {
            '0': 1,
            '-1': 1,
            '1': 2,
            '2': 3
          };
          data.voiceDuration = payTypeMao[data.voiceDuration];
        }
        data.payType = data.payType || data.voiceDuration; //发送的消息是没有payType
        data.prodType = data.prodType || data.subProdType; //
        data.presale = data.amount || data.presale;
        if (data.subProdType == 200 || data.subProdType == 92) {
          //带货优惠券
          if (data.payType == 2) {
            this.setData({
              commerceFloatInfo: data,
              isShowCommerceFloat: true
            })
          } else {
            this.setData({
              commerceFloatCouponInfo: data,
              isShowCommerceCouponFloat: true
            })
          }
        } else {
          this.setData({
            commerceFloatInfo: data,
            isShowCommerceFloat: true
          })
        }
        //带货弹框显示刷新
        if (this.selectComponent("#J_commerce-stu").data.isShow) {
          this.selectComponent("#J_commerce-stu").refreshData();
        }
      } else if (data.msgType == 22 || data.msgType == 73) {
        data.userName = liveInfo.isHideUserName ? this.hiddenUserName(data.userName) : data.userName;
        //打赏现金和实物
        if (socialInfo.showReward == 0) {
          //关闭
          isAddToChatList = false;
          isAddToTeacherChatList = false;
        } else if (socialInfo.showReward == 2) {
          //对讲师、管理员和购买者可见
          if (roles.isTeacher || roles.isAdmin) {
            isAddToTeacherChatList = true;
            isAddToChatList = true;
            if (data.msgType == 73) {
              this._rewardAnimMsgStock.push(data)
              this.rewardAnim();
            }
          } else if (data.jiguangUserName == socialInfo.jiguangUserName) {
            isAddToChatList = true; //打赏者
            isAddToTeacherChatList = false;
            if (data.msgType == 73) {
              this._rewardAnimMsgStock.unshift(data)
              this.rewardAnim();
            }
          } else if (data.jiguangUserName != socialInfo.jiguangUserName) {
            isAddToChatList = false; //非打赏者
            isAddToTeacherChatList = false;
          }
        } else {
          if (data.msgType == 73) {
            if (data.jiguangUserName == socialInfo.jiguangUserName) {
              this._rewardAnimMsgStock.unshift(data)
            } else {
              this._rewardAnimMsgStock.push(data)
            }
            this.rewardAnim();
          }
        }
      } else if (data.msgType == 74 || data.msgType == 75) {
        //已经购买的消息、正在购买的消息（后台开关控制是否显示）
        if (socialInfo.showBuyGoods == 0) {
          //对所有人不可见
          isAddToChatList = false;
          isAddToTeacherChatList = false;
        } else if (socialInfo.showBuyGoods == 2) {
          //对讲师、管理员和购买者可见
          if (this.roles.isTeacher || this.roles.isAdmin) {
            isAddToTeacherChatList = true;
            isAddToChatList = true;
          } else if (data.jiguangUserName == socialInfo.jiguangUserName) {
            isAddToChatList = true; //打赏者
            isAddToTeacherChatList = false;
          } else if (data.jiguangUserName != socialInfo.jiguangUserName) {
            isAddToChatList = false; //非打赏者
            isAddToTeacherChatList = false;
          }
        } else {
          //对所有人可见
          isAddToTeacherChatList = true;
        }
      } else if (data.msgType == 76) {
        //@功能消息

      } else if (data.msgType == 80) {
        //收到发送红包消息
        data.talkType = 1;
        data.redStatus = 1;
        data.isReceivedRedEnv = 0;
      } else if (data.msgType == 81) {
        if ((msgRoles.isAdmin || msgRoles.isTeacher) && data.redFromUserId == socialInfo.jiguangUserName) {
          isAddToTeacherChatList = true;
        } else if (data.jiguangUserName != socialInfo.jiguangUserName) {
          return;
        }
      }
      console.log("是否添加讨论区:", isAddToChatList, "是否添加授课区:", isAddToTeacherChatList, data)
      // @@
      if (isAddToTeacherChatList) {
        if (!this._isTeaChatListPullUpHasMore) {
          this.data.teaChatList.push(data);
          this.setData({
            teaChatList: this.data.teaChatList
          })
        }
      }

      if (isAddToChatList) {
        if (!this._isChatListPullUpHasMore) {
          this.data.chatList.push(data)
          this.setData({
            chatList: this.data.chatList
          }, () => {
            if (this._isDmScrollAtBottom) {
              this.dmScrollToBottom()
            } else {
              this.data.newMsgStack.push(data);
              this.setData({
                newMsgStack: this.data.newMsgStack
              })
            }
          });
        } else {
          this.data.newMsgStack.push(data);
          this.setData({
            newMsgStack: newMsgStack
          })
        }
      }
    } else {
      if (data.msgType == 23) {
        //直播开始
        this.setData({
          ['liveInfo.status']: 1
        }, () => {
          this._playerCtx = wx.createLivePlayerContext("J_live-player");
          setTimeout(() => {
            this.playerPlay();
          }, 500)
        });
      } else if (data.msgType == 72) {
        //刷新人数
        if (this.data.moduleType == 2) {
          this.setData({
            ['liveInfo.watchNum']: data.content
          })
        } else {
          this.setData({
            ['socialInfo.viewers']: data.content
          })
        }
      } else if (data.msgType == 85) {
        this.setData({
          ['liveInfo.isShowLike']: data.content
        })
      } else if (data.msgType == 94) {
        //打开二维码
        this.openGuidanceQrCode();
      } else if (data.msgType == 201) {
        //开始推流
        this.setData({
          ['liveInfo.invalidFlowStatus']: 1
        })
        if (this.data.liveInfo.status == 1) {
          this.playerPlay();
        }
      } else if (data.msgType == 202) {
        //中断推流
        this.setData({
          ['liveInfo.invalidFlowStatus']: -1
        });
        // this._stopLiveTimeCount();
        this.recordWatchCount();
      } else if (data.msgType == 204) {
        //连麦-邀请或者同意申请204
        if (data.toUser == socialInfo.jgInit.userId) {
          if (this._joinLiveStatusResetTimer) {
            clearTimeout(this._joinLiveStatusResetTimer);
            this._joinLiveStatusResetTimer = null;
          }
          this.setData({
            'liveInfo.joinLiveStatus': 2,
            'liveInfo.mikeCodeUrl': data.content,
            isShowLianMaiQrcodeModal: true
          })
        }
      } else if (data.msgType == 212) {
        //连麦-老师取消邀请212
        if (data.toUser == socialInfo.jgInit.userId) {
          this.setData({
            'liveInfo.joinLiveStatus': 0,
            isShowLianMaiQrcodeModal: false
          });
        }
      } else if (data.msgType == 208) {
        //连麦-用户加入房间占用名额208
        if (data.toUser == socialInfo.jgInit.userId) {
          this.setData({
            'liveInfo.joinLiveStatus': 3,
            isShowLianMaiQrcodeModal: false
          });
        }
      } else if (data.msgType == 209) {
        //连麦-上麦209
        if (data.toUser == socialInfo.jgInit.userId) {
          if (!roles.isAdmin) {
            if (roles.isNormal && data.content && liveInfo.joinLiveStatus != 3) {
              this.setData({
                'liveInfo.mikeCodeUrl': data.content
              })
            }
            this.setData({
              'liveInfo.joinLiveStatus': 4
            })
          }
          this.setData({
            isShowLianMaiQrcodeModal: true
          })
        }
      } else if (data.msgType == 210) {
        //连麦-下麦210 
        if (data.toUser == socialInfo.jgInit.userId) {
          this.setData({
            'liveInfo.joinLiveStatus': 3
          })
        }
      } else if (data.msgType == 211) {
        //连麦-讲师将学员下线211
        if (data.toUser == socialInfo.jgInit.userId) {
          this.setData({
            'liveInfo.joinLiveStatus': 0,
            isShowLianMaiQrcodeModal: false
          })
        }
      } else if (data.msgType == 260) {
        //抢麦-老师开启或者关闭(占用名额(joinLiveStatus >=3)不清空，其他状态一律0)
        if (roles.isNormal) {
          if (data.content.isShow) {
            //开启抢麦
            if (liveInfo.joinLiveStatus < 3) {
              this.setData({
                'liveInfo.joinLiveStatus': 0,
              })
            }
            if (this.data.liveInfo.mikeApplyStatus == 2 && !this.data.liveInfo.isVip) {
              //会员连麦，自己是非会员，弹出购买提示
              wx.showModal({
                title: '',
                content: '讲师发起了抢麦，开通会员后方可连麦',
                complete: (res) => {
                  if (res.confirm) {
                    this.openContactGuide({
                      prodType: 1,
                      socialRoomId: this.data.socialRoomId
                    });
                  }
                }
              })
              return;
            }
            if (this._joinLiveStatusResetTimer) {
              clearTimeout(this._joinLiveStatusResetTimer);
              this._joinLiveStatusResetTimer = null;
            }
            this.setData({
              graspMicTimeCount: data.content.time,
              graspMicSetTime: data.content.time,
              isShowLmGraspModal: true
            })
          } else {
            this.setData({
              graspMicTimeCount: 0,
              graspMicSetTime: 0,
              isShowLmGraspModal: false
            })
          }
        }
      } else if(data.msgType == 261){
        this.setData({
          'liveInfo.mikeApplyStatus': data.content
        })
      } else if (data.msgType == 277) {
        //上架
        let stuComp = this.selectComponent("#J_commerce-stu");
        let teaComp = this.selectComponent("#J_commerce-tea")
        if (stuComp && stuComp.data.isShow) {
          stuComp.refreshData();
        }
        if (teaComp && teaComp.data.isShow) {
          teaComp.refreshData();
        }
      } else if (data.msgType == 278 || data.msgType == 276) {
        //下架或者移除
        let stuComp = this.selectComponent("#J_commerce-stu");
        let teaComp = this.selectComponent("#J_commerce-tea");
        let commerceFloatInfo = this.data.commerceFloatInfo;
        let commerceFloatCouponInfo = this.data.commerceFloatCouponInfo;

        console.log("commerceFloatInfo", commerceFloatInfo, commerceFloatCouponInfo)
        if (stuComp && stuComp.data.isShow) {
          stuComp.refreshData();
        }
        if (teaComp && teaComp.data.isShow) {
          teaComp.refreshData();
        }
        //带货浮窗
        if ((commerceFloatInfo.prodId == data.prodId || commerceFloatInfo.subMsgId == data.prodId) && commerceFloatInfo.relationType == data.relationType) {
          this.setData({
            isShowCommerceFloat: false
          })
        } else if ((commerceFloatCouponInfo.prodId == data.prodId || commerceFloatCouponInfo.subMsgId == data.prodId) && commerceFloatCouponInfo.relationType == data.relationType) {
          this.setData({
            isShowCommerceCouponFloat: false
          })
        }
      } else if (data.msgType == 270) {
        //抽奖-关闭
        this.selectComponent("#luckyDrawStu").hide();
        this.setData({
          'liveInfo.isOpenLottery': false
        })
      } else if (data.msgType == 271) {
        //抽奖-开始
        if (!roles.isTeacher && !roles.isAdmin) {
          this.selectComponent("#luckyDrawStu").show(data.content);
        }
      } else if (data.msgType == 272) {
        //抽奖-开奖
        if (roles.isGuest || roles.isNormal) {
          this.selectComponent("#luckyDrawStu").hide();
          console.log(this.data.currLuckyDraw)
          if (this.data.currLuckyDraw.lotteryJoin) {
            //学员参与抽奖才显示抽奖结果
            this.selectComponent("#attendResult").show({
              id: data.content * 1,
              activityType: 64
            });
            this.setData({
              currLuckyDraw: {}
            })
          } else {
            this.setData({
              currLuckyDraw: {}
            })
          }
        } else {
          this.selectComponent("#luckyDrawTea").hideDetail();
          this.selectComponent("#attendPrizeRoster").show(data.content * 1);
        }
      } else if (data.msgType == 273) {
        //抽奖-取消
        this.selectComponent("#luckyDrawStu").hide();
        this.setData({
          currLuckyDraw: {}
        })
      } else if (data.msgType == 2000) {
        //连麦-老师开启或关闭连麦
        data.content = data.content * 1;
        this.setData({
          'liveInfo.isAllowMike': data.content,
        });
        if (!data.content) {
          this.setData({
            isShowLianMaiQrcodeModal: false
          })
        }
      } else if (data.msgType == 84) {
        this.data.likeNum = this.data.likeNum + data.content;
        this.setData({
          likeNum: this.data.likeNum
        })
        this.showOverTenThousand()
        this.selectComponent("#praiseHeartBy").public_addPraiseheartBy(data.content);
      }
    }
  },

  _setGroupTaboo(val) {
    let flag = false;
    switch (val * 1) {
      case 0:
        flag = false;
        break;
      case 2:
        flag = true;
        break;
    }
    this.setData({
      isGroupTaboo: flag
    }, () => {
      this._setInputObj();
    })
  },
  //群禁言切换
  switchChangeGroupTaboo(e) {
    console.log(e);
    let val = e.detail.value;
    let memberPrivileges = val ? 2 : 0;
    utils.post('social/setPrivileges/', {
      socialRoomId: this.data.socialRoomId,
      memberPrivileges: memberPrivileges
    }, false).then(() => {
      this.setData({
        isGroupTaboo: val
      });
      IM.sendCustomMessage({
        ...this._imSendDefaultData,
        socialRoomMessageId: Date.now(),
        msgType: 11,
        content: memberPrivileges
      })
    })
  },
  //切换点赞
  switchChangePraise(e) {
    console.log(this.data.liveInfo.isShowLike)
    let val = e.detail.value;
    let praiseVal = val ? 1 : 0;
    utils.post(`live/livePersonal/setLiveLike/${this.data.liveId}`, {
      moduleType: 1,
      isShowLike: praiseVal
    }, false).then(() => {
      this.setData({
        ['liveInfo.isShowLike']: praiseVal
      });
      IM.sendCustomMessage({
        ...this._imSendDefaultData,
        msgType: 85,
        socialRoomMessageId: new Date().getTime(),
        content: praiseVal
      })
    })
  },
  //改变直播观看人数
  changeLiveViewCount(e) {
    if (this.data.moduleType == 2) {
      this.setData({
        ['liveInfo.watchNum']: e.detail
      })
    } else {
      this.setData({
        ['socialInfo.viewers']: e.detail
      })
    }
  },
  showOverTenThousand() {
    if (this.data.likeNum >= 10000 && this.data.likeNum < 10000000) {
      let showNum = this.data.likeNum / 10000;
      if (this.data.likeNum % 10000 == 0) {
        showNum = showNum + '.0';
      }
      this.setData({
        overTenThousand: showNum.toString().match(/^\d+(?:\.\d{0,1})?/) + 'w'
      });
    } else if (this.data.likeNum >= 10000000) {
      this.setData({
        overTenThousand: parseInt(this.data.likeNum / 10000) + 'w'
      });
    } else {
      this.setData({
        overTenThousand: this.data.likeNum
      });
    }
  },
  _savePraiseToServer(num) {
    return new Promise((resolve, reject) => {
      let sendData = {
        likeNum: num
      };
      if (this.data.moduleType == 2) {
        sendData.detailId = this.data.detailId
      }
      utils.post(`live/livePersonal/saveLikeNum/${this.data.liveId}`, sendData, () => {
        resolve();
      }, () => {
        reject();
      });
    });
  },
  //点赞
  praise() {
    this.data.praiseNUm++; //点赞发送数
    this.data.likeNum++; //点赞数
    this.setData({
      praiseNUm: this.data.praiseNUm,
      likeNum: this.data.likeNum
    });
    this.showOverTenThousand()
    console.log(this.data.praiseTimer, this.data.praiseNUm, this.data.likeNum);
    this.selectComponent("#praiseHeart").public_addPraise(this.data.praiseNUm);
    if (!this.data.praiseTimer) {
      this.data.praiseTimer = setTimeout(() => {
        //保存服务端
        console.log(this.data.praiseNUm);
        this._savePraiseToServer(this.data.praiseNUm);
        //发送消息
        if (this.data.liveInfo.status == 0 || this.data.liveInfo.status == 1) {
          IM.sendCustomMessage({
            ...this._imSendDefaultData,
            msgType: 84, //消息类型 图片 文字 语音  禁言 拉黑用户
            content: this.data.praiseNUm, //消息内容 语音和图片为对应src 文字为文本
          });
        }
        this.data.praiseTimer = null;
        this.data.praiseNUm = 0;
        this.setData({
          praiseTimer: null,
          praiseNUm: 0
        });
      }, 1000);
      this.setData({
        isPraiseAniming: true
      })
    }
  },
  praiseAniming() {
    this.setData({
      isPraiseAniming: false
    })
  },
  jumpToBack() {
    wx.navigateBack();
  },
  /*
   *  ┌─────────────────────────────────────────────────────────────┐
   *  @@ 抽奖相关 start
   *  └─────────────────────────────────────────────────────────────┘
   *  
   */
  openAttendPrizeList() {
    this.selectComponent("#attendPrizeList").show({
      type: 64
    });
  },
  //校对luck
  luckyDrawChange(e) {
    console.log(e);
    let data = e.detail;
    if (data && data.lotteryId) {
      this.setData({
        currLuckyDraw: {
          lotteryId: data.lotteryId, //当前正在抽奖的id
          lotteryDrawAt: data.lotteryDrawAt,
          lotteryDownCount: utils.dtFormat(data.lotteryDrawAt * 1000, 'mm:ss'),
          lotteryJoin: data.lotteryJoin
        }
      }, () => {
        this._ldcTimer && clearTimeout(this._ldcTimer);
        this._luckyDrawDownCount();
      })
    } else {
      clearTimeout(this._ldcTimer);
      this._ldcTimer = null;
      this.setData({
        'currLuckyDraw.lotteryDrawAt': 0,
        'currLuckyDraw.lotteryDownCount': 0
      })
    }
    this.setData({
      isShowMore: false
    })
  },
  openLuckyDraw() {
    if (this.data.roles.isAdmin || this.data.roles.isTeacher) {
      this.selectComponent("#luckyDrawTea").showDetail(this.data.currLuckyDraw.lotteryId);
    } else {
      this.selectComponent("#luckyDrawStu").show(this.data.currLuckyDraw.lotteryId);
    }
  },
  //打开抽奖福利
  openWelfare() {
    this.selectComponent("#welfare").show();
  },
  //设置可领取的福利数量
  setWelfareEnableNum(e) {
    this.setData({
      welfareNum: e.detail
    })
  },
  //打开福利奖品详情
  openWelfarePrizeDetail(e) {
    let detail = e.detail;
    console.log(e);
    this.selectComponent("#attendResult").show(detail);
  },


  //打开中奖表单
  openAttendPrizeRoster(e) {
    console.log("openAttendPrizeRoster", e);
    this.selectComponent("#attendPrizeRoster").show(e.detail.id)
  },
  _luckyDrawDownCount() {
    let currLuckyDraw = this.data.currLuckyDraw;
    if (currLuckyDraw.lotteryDrawAt < 1 || !currLuckyDraw.lotteryDrawAt) {
      clearTimeout(this._ldcTimer);
      //不限时间，不关闭
      this._ldcTimer = null;
      this.setData({
        'currLuckyDraw.lotteryDrawAt': 0,
        'currLuckyDraw.lotteryDownCount': 0
      });
    } else {
      currLuckyDraw.lotteryDrawAt--;
      currLuckyDraw.lotteryDownCount = utils.dtFormat(currLuckyDraw.lotteryDrawAt * 1000, 'mm:ss');
      this.setData({
        currLuckyDraw: currLuckyDraw
      })
      this._ldcTimer = setTimeout(() => {
        this._luckyDrawDownCount();
      }, 1000);
    }
  },

  //打开打赏弹框
  openReward() {
    this.selectComponent("#reward").show();
  },









  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let fromPage = utils.getStorage("fromPage");
    if (fromPage == 1) {
      //支付成功页面
      this.setData({
        isShowMallSpecs: false,
        isShowStuCommerceList: false,
        isShowOtherPlaceOrder: false,
        isShowMallPlaceOrder: false,
      });
      let prizeListComponent = this.selectComponent("#attendPrizeList");
      if (prizeListComponent && prizeListComponent.data.isShow) {
        prizeListComponent.refresh();
      }
      let attendResultComponent = this.selectComponent("#attendResult");
      if (prizeListComponent) {
        attendResultComponent.hideAll();
      }
      let rewardComponent = this.selectComponent("#reward");
      if (rewardComponent) {
        rewardComponent.hide();
      }
      utils.removeStorage("fromPage")
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    if (this.data.liveInfo.status >= 2 && this._videoCurrentTime) {
      //回放的时候
      this._recordMemoryTime(this._videoCurrentTime);
    }
    IM.offMsgReceived();
    let companyShare = this.data.companyShare;
    if (companyShare.companyAuth && companyShare.companyAuth.enableWatchLiveFlowPoint == 1 && companyShare.companyAuth.pointModel == 1 && this._liveGetPointTimeCount >= 60) {
      this.getWatchIntegration(54)
    }
    this._stopLiveTimeCount();
    // IM.logout();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
})